bash:使用 scp 检查远程文件是否存在
我正在编写一个 bash 脚本来将文件从远程服务器复制到本地计算机。我需要检查该文件是否可用,以便在该文件不存在时可以采取替代操作。
我知道如何测试本地文件是否存在,但是,使用 scp 会使事情变得有点复杂。常识告诉我,一种方法是无论如何尝试 scp 文件,并检查 scp 命令的返回代码。这是正确的做法吗?
如果是,如何测试 scp 调用的返回代码?
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.
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?
If yes, how do I test the return code from the scp invocation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 ssh + cmd 行中嵌入的一些 shell 代码;当您需要在文件传输失败之前做出决定时,请使用此方法;
如果你想传输目录,你可能需要先“tar”它,
如果你想使用 scp,你可以检查返回代码,如下所示:
这实际上取决于知道文件是否存在对你来说很重要;在传输开始之前(使用 ssh+sh)或完成之后。
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;
if you want to transfer directories you may want to "tar"-it first
if you want to use scp you can check the return code like this:
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.
好吧,既然您可以使用
scp
,您可以尝试使用ssh
列出并查看该文件是否是他们的,然后再继续。well, since you can use
scp
you can try usingssh
to list and see if the file is their or not before proceeding.在执行 scp 之前,您必须运行 ssh 命令并检查文件或目录。我正在使用 stat 命令来验证文件/目录是否存在。我编写的用于检查和传输文件的脚本是
如果 SSH 不能以这种方式工作并要求输入密码,请考虑在任何 ssh 或 scp 命令之前使用 sshpass,并且您必须这样写:
不要忘记通过brew 在您的计算机上安装 sshpass或 apt
另外,如果您要检查的文件不存在于同一目录中,则像这样检查文件
You have to run ssh command and check for file or directory before doing a scp. I am using stat command to verify existance of file/directory. The script that I wrote to check and transfer file is
If SSH does not work this way and ask for password consider using sshpass before any ssh or scp command and you would have to write like
Don't forget to install sshpass on your machine via brew or apt
Additionally if the file you are checking does not exist in same directory than check file like this