我看到了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)
该$( ... )构造执行命令并返回命令的退出状态及其作为字符串的输出。这是一个更现代的反引号版本`...`。
它可以像这样使用: 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)
| 归档时间: |
|
| 查看次数: |
2493 次 |
| 最近记录: |