当if中的条件表达式是bash脚本中的命令时,它是什么意思?



当我像下面这样编写bash脚本时:

file_path="/workspace/output.bin"
file_path_="/workspace/output_.bin"
if cmp -s "$file_path" "$file_path_"; then
continue
fi

我认为条件是cmp命令的返回值,所以上面的if表达式表示当output.binoutput_.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

否则需要elifelse块。


使用!的否定不限于/附加到if子句/语句,您可以这样做:

! cmp -s "$file_path" "$file_path_" 
echo $?

&&||也适用于这个表达式,

  • 参见LESS='+/Compound Commands' man bash
  • LESS='+/EXIT STATUS' man bash
  • 参见退出状态
  • 参见条件构式

最新更新