Bash: return if 语句中的代码导致意外行为
Bash: return code in if statement causes unexpected behavior
我正在使用 cmp
命令检查两个文件是否相同。我想将命令粘贴到一行 if 语句中,但它没有按预期工作。当比较两个文件和一个不存在的文件时,cmp
returns 2。由于 2 不为零,我希望 if 语句的计算结果为真,但事实并非如此,我也没有不明白为什么。
我想写这样的东西:
if cmp -s tickets.txt tickets_orig.txt; then
#do stuff here
fi
因为我觉得它简短、亲切且更直观。这可能吗?
我可以使用 $?
创建一个解决方法,但我不明白为什么下面的代码会计算为 true 而上面的代码会在命令 returns 时计算为 false 2:
cmp -s tickets.txt tickets_orig.txt
if [ $? -ne 0 ]; then
#do stuff here
fi
退出状态($?) = 0表示shell逻辑成功,它允许为正常状态定义不同的错误代码1到127
if command; then #...
等同于
command;
if [ $? -eq 0 ]; then #...
和
command;
if [ $? -ne 0 ]; then #...
相当于
if ! command; then #...
我正在使用 cmp
命令检查两个文件是否相同。我想将命令粘贴到一行 if 语句中,但它没有按预期工作。当比较两个文件和一个不存在的文件时,cmp
returns 2。由于 2 不为零,我希望 if 语句的计算结果为真,但事实并非如此,我也没有不明白为什么。
我想写这样的东西:
if cmp -s tickets.txt tickets_orig.txt; then
#do stuff here
fi
因为我觉得它简短、亲切且更直观。这可能吗?
我可以使用 $?
创建一个解决方法,但我不明白为什么下面的代码会计算为 true 而上面的代码会在命令 returns 时计算为 false 2:
cmp -s tickets.txt tickets_orig.txt
if [ $? -ne 0 ]; then
#do stuff here
fi
退出状态($?) = 0表示shell逻辑成功,它允许为正常状态定义不同的错误代码1到127
if command; then #...
等同于
command;
if [ $? -eq 0 ]; then #...
和
command;
if [ $? -ne 0 ]; then #...
相当于
if ! command; then #...