bash:使用scp检查远程文件是否存在 [英] bash: check if remote file exists using scp

查看:78
本文介绍了bash:使用scp检查远程文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个bash脚本,以将文件从远程服务器复制到本地计算机.我需要检查文件是否可用,所以如果文件不存在,我可以采取另一种措施.

I am writing a bash script to copy a file from a remote server, to my local machine. I need to check to see if the file is available, so I can take an alternative action if it is not there.

我知道如何测试本地文件是否存在,但是,使用scp会使事情变得有些复杂.常识告诉我,一种方法是尝试以任何方式对文件进行scp,然后检查来自scp命令的返回代码.这是正确的解决方法吗?

I know how to test if a local file exists, however, using scp complicates things a bit. Common sense tells me that one way would be to try to scp the file anyhow, and check the return code from the scp command. Is this the correct way to go about it?

如果是,我如何测试来自scp调用的返回代码?

If yes, how do I test the return code from the scp invocation?

推荐答案

使用ssh +嵌入在cmd行中的一些shell代码;需要在文件传输失败之前做出决定时使用此方法;

using ssh + some shell code embedded in the cmd line; use this method when you need to take a decision before the file transfer will fail;

ssh remote-host 'sh -c "if [ -f ~/myfile ] ; then gzip -c ~/myfile ; fi" ' | gzip -dc > /tmp/pkparse.py

如果您要转移目录,则可能要先"tar"

if you want to transfer directories you may want to "tar"-it first

如果要使用scp,可以检查返回代码,如下所示:

if you want to use scp you can check the return code like this:

if scp remote-host:~/myfile ./ >&/dev/null ; then echo "transfer OK" ; else echo "transfer failed" ; fi

这实际上取决于何时知道文件是否存在很重要;在传输开始之前(使用ssh + sh)或传输完成之后.

it really depends on when its important for you to know if the file is there or not; before the transfer starts (use ssh+sh) or after its finished.

这篇关于bash:使用scp检查远程文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆