if $( ssh user@host " [ -e file ] " ); 中的“if $”是什么意思?然后 ...?

avs*_*sun 2 shell-script

我看到了if语句中条件使用 a 的脚本,但$ 我不明白为什么?

if $( ssh user@host " test -e file  " ); then 
   echo "File is there"
else
   echo "We don't that file on that host"
fi
Run Code Online (Sandbox Code Playgroud)

che*_*ner 12

$(...)是命令替换。shell 运行包含的命令,表达式被命令的标准输出替换。

通常,如果替换文本没有命名 shell 可以运行的命令,这将产生错误。但是,不test产生任何输出,因此结果是外壳“跳过”的空字符串。例如,考虑如果您运行

if $( ssh user@host " echo foo " ); then 
   echo "File is there"
else
   echo "We don't that file on that host"
fi
Run Code Online (Sandbox Code Playgroud)

给定的代码正确编写,没有不必要的命令替换;该if语句唯一需要的是命令的退出状态。

if ssh user@host "test -e file"; then 
   echo "File is there"
else
   echo "We don't that file on that host"
fi
Run Code Online (Sandbox Code Playgroud)

  • +1。请注意,`test` 不会产生任何输出,但是如果远程用户的登录 shell 是 csh/tcsh/bash,那么 `~/.<shell>rc` 文件将被解释并且可能会产生一些输出。在任何情况下,我都会在你的 _is 更正确地写_中删除 _more_。执行 `if $(ssh user@host "test -e file")` 没有任何意义。如果`user` 的帐户在`host` 上被盗用(或者你不信任他),就会有安全隐患。 (3认同)

roa*_*ima 6

$( ... )构造执行命令并返回命令的退出状态及其作为字符串的输出。这是一个更现代的反引号版本`...`

它可以像这样使用: my_id=$(id)

不过,您发布的代码段是损坏的代码。它使用 的结果ssh user@host "test -f file",它似乎根据远程主机上文件的存在返回一个布尔值。不幸的是,它没有考虑到它ssh本身可能会失败:

if $(ssh -q localhost true); then echo YES; else echo NO; fi
YES

if $(ssh -q localhost false); then echo YES; else echo NO; fi
NO

if $(ssh -q nowhere true); then echo YES; else echo NO; fi
ssh: Could not resolve hostname nowhere: Name or service not known
NO
Run Code Online (Sandbox Code Playgroud)

也许这是有意的行为,但我怀疑不是。

此外,$( ... )是多余的,条件可以更好地直接表达:

if ssh -q user@host "test -e file"; then 
   echo "File is there"
else
   echo "We don't [see] that file on that host [or the ssh failed]"
fi
Run Code Online (Sandbox Code Playgroud)