bash:使用 scp 检查远程文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5455605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash: check if remote file exists using scp
提问by oompahloompah
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.
我正在编写一个 bash 脚本来将文件从远程服务器复制到我的本地机器。我需要检查该文件是否可用,如果它不存在,我可以采取替代操作。
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 会使事情变得有点复杂。常识告诉我,一种方法是尝试以任何方式 scp 文件,并检查 scp 命令的返回码。这是正确的方法吗?
If yes, how do I test the return code from the scp invocation?
如果是,我如何测试 scp 调用的返回码?
采纳答案by user237419
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 + 一些嵌入在 cmd 行中的 shell 代码;当您需要在文件传输失败之前做出决定时使用此方法;
ssh remote-host 'sh -c "if [ -f ~/myfile ] ; then gzip -c ~/myfile ; fi" ' | gzip -dc > /tmp/pkparse.py
if you want to transfer directories you may want to "tar"-it first
如果您想传输目录,您可能需要先“tar”-it
if you want to use scp you can check the return code like this:
如果你想使用 scp 你可以像这样检查返回码:
if scp remote-host:~/myfile ./ >&/dev/null ; then echo "transfer OK" ; else echo "transfer failed" ; fi
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.
这实际上取决于何时对您来说知道文件是否存在很重要;在传输开始之前(使用 ssh+sh)或传输完成之后。
回答by kurumi
well, since you can use scpyou can try using sshto list and see if the file is their or not before proceeding.
好吧,既然您可以使用,scp您可以尝试使用ssh列出并在继续之前查看文件是否是他们的。

