bash: check if remote file exists using scp

空扰寡人 提交于 2020-06-24 11:32:21

问题


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?


回答1:


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

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:

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.




回答2:


well, since you can use scp you can try using ssh to list and see if the file is their or not before proceeding.



来源:https://stackoverflow.com/questions/5455605/bash-check-if-remote-file-exists-using-scp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!