当我像下面这样编写bash脚本时:
file_path="/workspace/output.bin"
file_path_="/workspace/output_.bin"
if cmp -s "$file_path" "$file_path_"; then
continue
fi
我认为条件是cmp
命令的返回值,所以上面的if表达式表示当output.bin
和output_.bin
不同时执行continue
,否则跳过continue
。
但实际上,bash的执行行为完全相反。当两个文件相同时,continue
将执行。为什么?
或者if条件是什么意思?
根据
help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.
The `if COMMANDS' list is executed. If its exit status is zero, then the
`then COMMANDS' list is executed. Otherwise, each `elif COMMANDS' list is
executed in turn, and if its exit status is zero, the corresponding
`then COMMANDS' list is executed and the if command completes. Otherwise,
the `else COMMANDS' list is executed, if present. The exit status of the
entire construct is the exit status of the last command executed, or zero
if no condition tested true.
Exit Status:
Returns the status of the last command executed.
所以在你的情况下,如果cmp
的退出状态为真(零):
cmp -s "$file_path" "$file_path_"
echo $?
应该返回0
,如果它们是相同的,这意味着true
如果您的系统中的cmp
支持--help
标志:
cmp --help | grep '^Exit status'
输出Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.
- 参见POSIX cmp
现在根据help test
help test | grep -F '! EXPR'
输出! EXPR True if expr is false.
!
bang否定,表示退出状态是反向的。
这意味着你可以这样做:
if ! cmp -s "$file_path" "$file_path_"; then
continue
fi
否则需要elif
或else
块。
使用!
的否定不限于/附加到if
子句/语句,您可以这样做:
! cmp -s "$file_path" "$file_path_"
echo $?
&&
和||
也适用于这个表达式,
- 参见
LESS='+/Compound Commands' man bash
- 见
LESS='+/EXIT STATUS' man bash
- 参见退出状态
- 参见条件构式