Gra*_*ner -1 bash boolean-logic
我试图理解以下代码:
for f in *.out; do sort -cg <$f &>/dev/null && res="sorted" || res="unsorted"; echo "File $f is $res."; done
Run Code Online (Sandbox Code Playgroud)
For 循环遍历所有.out
文件并将每个文件作为参数给出sort
,排序的输出被重定向为“nothing”。但有人能解释一下&& res="sorted" || res="unsorted"
吗?
&&
仅当前一个命令以 0(零)状态代码退出时,才会执行后的命令。另一个||
以相反的方式工作 - a 之后的命令||
仅当前一个命令以非零退出代码退出时才会执行。
这是一个小例子:
cat /some/file/that/is/missing && echo 'Found the file!' # doesn't print
cat /some/file/that/is/missing || echo 'Unable to find the file!' # will print
Run Code Online (Sandbox Code Playgroud)
对于第一行,该echo
命令将不会执行,因为cat
命令失败(因为该文件不存在)
在第二行中,我们将看到该echo
命令,因为该cat
命令失败了。