如何退出,如果一个命令失败? [英] How to exit if a command failed?
问题描述
我在的shell脚本一个小白。我想打印一个消息,如果一个命令失败退出我的脚本。我试过:
I am a noob in shell-scripting. I want to print a message and exit my script if a command fails. I've tried:
my_command && (echo 'my_command failed; exit)
,但它不工作。它使执行下面这行脚本的说明。我在使用Ubuntu和bash。
but it does not work. It keeps executing the instructions following this line in the script. I'm using Ubuntu and bash.
推荐答案
尝试:
my_command || { echo 'my_command failed' ; exit 1; }
四大变化:
- 更改
&放大器;&安培;
到||
- 使用
{}
在的()
- 介绍
;
在退出
和 - 空格后
{
和前}
- Change
&&
to||
- Use
{ }
in place of( )
- Introduce
;
afterexit
and - spaces after
{
and before}
既然你要打印的消息,只有当命令失败(非零值退出)退出你需要一个 ||
不是&功放;&安培;
Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a ||
not an &&
.
cmd1 && cmd2
运行时 CMD1
成功(退出值 CMD2
0
)。凡为
will run cmd2
when cmd1
succeeds(exit value 0
). Where as
cmd1 || cmd2
将运行 CMD2
在 CMD1
失败(退出值不为零)。
will run cmd2
when cmd1
fails(exit value non-zero).
使用()
使得它们内部的命令在 子shell 的并调用<$ C运行$ C>退出从那里使你退出子shell,而不是原来的壳,从而继续执行在原壳。
Using ( )
makes the command inside them run in a sub-shell and calling a exit
from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.
要克服这种使用 {}
最后的两个变化是由bash的要求。
The last two changes are required by bash.
这篇关于如何退出,如果一个命令失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!