如何在一行/语句中检查 bash 中的退出代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29312583/
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
How to check exit code in bash in one line/statement?
提问by Uli Kunkel
This is what I'm trying to do:
这就是我想要做的:
#!/bin/bash
set -e # I can't remove this line!
if [ docker inspect foo ]; then
echo container is present
else
echo container is absent
fi
Is it possible? docker inspect foo
returns exit code 1
when container is absent and 0
when it's present.
是否可以?当容器不存在和存在时docker inspect foo
返回退出代码。1
0
Now I'm getting this:
现在我得到这个:
-bash: [: too many arguments
回答by Kenster
If you want to run the command within the "if" statement, you'd do it like this:
如果你想在“if”语句中运行命令,你可以这样做:
if docker inspect foo
then
echo container is present
else
echo container is absent
fi
All of the line breaks can be omitted or replaced by semicolons if you want. This would also work:
如果需要,所有换行符都可以省略或替换为分号。这也可以:
if docker inspect foo; then echo container is present; else echo container is absent; fi
If you want something more compact, you could use this kind of syntax:
如果你想要更紧凑的东西,你可以使用这种语法:
docker inspect foo && echo container is present
docker inspect foo || echo container is absent
docker inspect foo && echo container is present || echo container is absent
&&
runs the second command if the first succeeded. ||
runs the second command if the first one failed. The last line uses both forms.
&&
如果第一个成功,则运行第二个命令。||
如果第一个命令失败,则运行第二个命令。最后一行使用了两种形式。