Bash“not”:反转命令的退出状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15073048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash "not": inverting the exit status of a command
提问by Coquelicot
I know I can do this...
我知道我可以做到这一点...
if diff -q $f1 $f2
then
echo "they're the same"
else
echo "they're different"
fi
But what if I want to negate the condition that I'm checking? i.e. something like this (which obviously doesn't work)
但是如果我想否定我正在检查的条件怎么办?即像这样的东西(这显然不起作用)
if not diff -q $f1 $f2
then
echo "they're different"
else
echo "they're the same"
fi
I could do something like this...
我可以做这样的事情......
diff -q $f1 $f2
if [[ $? > 0 ]]
then
echo "they're different"
else
echo "they're the same"
fi
Where I check whether the exit status of the previous command is greater than 0. But this feels a bit awkward. Is there a more idiomatic way to do this?
哪里检查上一条命令的退出状态是否大于0。不过这个感觉有点别扭。有没有更惯用的方法来做到这一点?
回答by William Pursell
if ! diff -q "$f1" "$f2"; then ...
回答by Gilles Quenot
If you want to negate, you are looking for !:
如果你想否定,你正在寻找!:
if ! diff -q $f1 $f2; then
echo "they're different"
else
echo "they're the same"
fi
or (simplty reverse the if/else actions) :
或(简单地反转 if/else 操作):
if diff -q $f1 $f2; then
echo "they're the same"
else
echo "they're different"
fi
Or also, try doing this using cmp:
或者,尝试使用cmp以下方法执行此操作:
if cmp &>/dev/null $f1 $f2; then
echo "$f1 $f2 are the same"
else
echo >&2 "$f1 $f2 are NOT the same"
fi
回答by Karoly Horvath
To negate use if ! diff -q $f1 $f2;. Documented in man test:
否定使用if ! diff -q $f1 $f2;。记录在man test:
! EXPRESSION
EXPRESSION is false
Not quite sure why you need the negation, as you handle both cases... If you only need to handle the case where they don't match:
不太确定为什么你需要否定,因为你处理这两种情况......如果你只需要处理它们不匹配的情况:
diff -q $f1 $f2 || echo "they're different"

