std*_*err 31 linux ssh bash shell
我想检查远程主机上是否存在某个文件.我试过这个:
$ if [ ssh user@localhost -p 19999 -e /home/user/Dropbox/path/Research_and_Development/Puffer_and_Traps/Repeaters_Network/UBC_LOGS/log1349544129.tar.bz2 ] then echo "okidoke"; else "not okay!" fi
-sh: syntax error: unexpected "else" (expecting "then")
Run Code Online (Sandbox Code Playgroud)
Flo*_*ciu 42
这是一个简单的方法:
if ssh $HOST stat $FILE_PATH \> /dev/null 2\>\&1
then
echo "File exists"
else
echo "File does not exist"
fi
Run Code Online (Sandbox Code Playgroud)
JP *_*Lew 41
除了上面的答案,还有简写方法:
ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist";
Run Code Online (Sandbox Code Playgroud)
-q
是安静模式,它会抑制警告和消息.
作为@Mat提到的,这样测试的一个好处是,你可以很容易地换出-f
你喜欢的任何测试操作:-nt
,-d
,-s
等...
测试运营商: http ://tldp.org/LDP/abs/html/fto.html
kar*_*rni 24
不能比这简单得多:)
ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
# your file exists
fi
Run Code Online (Sandbox Code Playgroud)
一行,适当引用
ssh remote_host test -f "/path/to/file" && echo found || echo not found
Run Code Online (Sandbox Code Playgroud)
你错过了;
.将所有内容放在一行中的一般语法是:
if thing ; then ... ; else ... ; fi
Run Code Online (Sandbox Code Playgroud)
该thing
可几乎任何返回退出代码.该then
如果分支被采用thing
返回0,该else
分支除外.
[
不是语法,它是test
程序(检查ls /bin/[
,它实际存在,man test
对于文档 - 虽然也可以有一个具有不同/附加功能的内置版本.),用于测试文件和变量的各种常见条件.(注意,[[
另一方面,语法是由shell处理的,如果它支持的话).
对于您的情况,您不想test
直接使用,您想要在远程主机上测试某些东西.所以尝试类似的东西:
if ssh user@host test -e "$file" ; then ... ; else ... ; fi
Run Code Online (Sandbox Code Playgroud)
测试文件是否存在:
HOST="example.com"
FILE="/path/to/file"
if ssh $HOST "test -e $FILE"; then
echo "File exists."
else
echo "File does not exist."
fi
Run Code Online (Sandbox Code Playgroud)
相反,测试文件是否不存在:
HOST="example.com"
FILE="/path/to/file"
if ! ssh $HOST "test -e $FILE"; then
echo "File does not exist."
else
echo "File exists."
fi
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
85406 次 |
最近记录: |