如何使用shell检查远程服务器上是否存在文件

Bra*_*ndy 5 shell

我已经做了很多搜索,我似乎无法使用shell脚本找出如何做到这一点.基本上,我是从远程服务器复制文件,如果不存在,我想做其他事情.我下面有一个数组,但我试图直接引用它,但它仍然返回false.

我是全新的,所以请善待:)

declare -a array1=('user1@user1.user.com');

for i in "${array1[@]}"
do
   if [ -f "$i:/home/user/directory/file" ];
   then
     do stuff
   else
     Do other stuff
   fi
done
Run Code Online (Sandbox Code Playgroud)

Eta*_*ner 2

假设您正在使用scpssh用于远程连接,类似这样的东西应该可以满足您的要求。

declare -a array1=('user1@user1.user.com');

for i in "${array1[@]}"; do
    if ssh -q "$i" "test -f /home/user/directory/file"; then
        scp "$i:/home/user/directory/file" /local/path
    else
        echo 'Could not access remote file.'
    fi
done
Run Code Online (Sandbox Code Playgroud)

或者,如果您不一定需要关心远程文件不存在和其他可能的scp错误之间的区别,那么以下方法可以工作。

declare -a array1=('user1@user1.user.com');

for i in "${array1[@]}"; do
    if ! scp "$i:/home/user/directory/file" /local/path; then
        echo 'Remote file did not exist.'
    fi
done
Run Code Online (Sandbox Code Playgroud)