我知道我可以这样做......
if diff -q $f1 $f2
then
echo "they're the same"
else
echo "they're different"
fi
但是,如果我想否定我正在检查的条件怎么办?即这样的事情(显然不起作用)
if not diff -q $f1 $f2
then
echo "they're different"
else
echo "they're the same"
fi
我可以做这样的事......
diff -q $f1 $f2
if [[ $? > 0 ]]
then
echo "they're different"
else
echo "they're the same"
fi
我检查上一个命令的退出状态是否大于0.但这感觉有点尴尬。有没有更惯用的方法呢?
答案 0 :(得分:9)
if ! diff -q $f1 $f2; then ...
答案 1 :(得分:1)
如果你想否定,你正在寻找!
:
if ! diff -q $f1 $f2; then
echo "they're different"
else
echo "they're the same"
fi
或(简化if / else动作的反转):
if diff -q $f1 $f2; then
echo "they're the same"
else
echo "they're different"
fi
或者,也可以尝试使用cmp
:
if cmp &>/dev/null $f1 $f2; then
echo "$f1 $f2 are the same"
else
echo >&2 "$f1 $f2 are NOT the same"
fi
答案 2 :(得分:1)
否定使用if ! diff -q $f1 $f2;
。记录在man test
:
! EXPRESSION
EXPRESSION is false
不完全确定为什么需要否定,因为你处理这两种情况......如果你只需要处理它们不匹配的情况:
diff -q $f1 $f2 || echo "they're different"