Bash“;“不是”的意思:反转命令的退出状态
我知道我能做到Bash“;“不是”的意思:反转命令的退出状态,bash,conditional,Bash,Conditional,我知道我能做到 if diff -q $f1 $f2 then echo "they're the same" else echo "they're different" fi 但是如果我想否定我正在检查的条件呢?i、 e.类似的东西(显然不起作用) 我可以这样做 diff -q $f1 $f2 if [[ $? > 0 ]] then echo "they're different" else echo "they're the same" fi 其中
if diff -q $f1 $f2
then
echo "they're the same"
else
echo "they're different"
fi
但是如果我想否定我正在检查的条件呢?i、 e.类似的东西(显然不起作用)
我可以这样做
diff -q $f1 $f2
if [[ $? > 0 ]]
then
echo "they're different"
else
echo "they're the same"
fi
其中,我检查上一个命令的退出状态是否大于0。但这感觉有点尴尬。有没有更惯用的方法呢?如果你想否定,你需要的是
代码>:
if ! diff -q $f1 $f2; then
echo "they're different"
else
echo "they're the same"
fi
或者(简单地反转if/else操作):
或者,也可以尝试使用cmp
:
if cmp &>/dev/null $f1 $f2; then
echo "$f1 $f2 are the same"
else
echo >&2 "$f1 $f2 are NOT the same"
fi
若要否定,请使用if!差异-q$f1$f2代码>。记录在人员测试中
:
! EXPRESSION
EXPRESSION is false
不太清楚为什么你需要否定,因为你处理这两种情况。。。如果您只需要处理它们不匹配的情况:
diff -q $f1 $f2 || echo "they're different"
但这实际上是在调用测试吗?我没有使用“test”或“[”。它没有调用它,它是一个shell内置(出于性能原因),但是语法是相同的man test
在这里是不相关的。Fromman bash
:\如果保留字!位于管道之前,则该管道的退出状态是上述退出状态的逻辑否定_
if ! diff -q "$f1" "$f2"; then ...
! EXPRESSION
EXPRESSION is false
diff -q $f1 $f2 || echo "they're different"