I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
相关问题
- How to get the return code of a shell script in lu
- JQ: Select when attribute value exists in a bash a
- Invoking Mirth Connect CLI with Powershell script
- Emacs shell: save commit message
- bash print whole line after splitting line with if
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Check if directory exists on remote machine with s
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- Reverse four length of letters with sed in unix
- Launch interactive SSH bash session from PHP
- BASH: Basic if then and variable assignment
In bash this is easy, just tie them together with &&:
You can also use the nested if construct:
After each command, the exit code can be found in the
$?
variable so you would have something like:You need to be careful of piped commands since the
$?
only gives you the return code of the last element in the pipe so, in the code:will not return an error code if the file doesn't exist (since the
sed
part of the pipeline actually works, returning 0).The
bash
shell actually provides an array which can assist in that case, that beingPIPESTATUS
. This array has one element for each of the pipeline components, that you can access individually like${PIPESTATUS[0]}
:Note that this is getting you the result of the
false
command, not the entire pipeline. You can also get the entire list to process as you see fit:If you wanted to get the largest error code from a pipeline, you could use something like:
This goes through each of the
PIPESTATUS
elements in turn, storing it inrc
if it was greater than the previousrc
value.for bash:
http://cfaj.freeshell.org/shell/cus-faq-2.html#11
How do I get the exit code of
cmd1
incmd1|cmd2
First, note that
cmd1
exit code could be non-zero and still don't mean an error. This happens for instance inyou might observe a 141 (or 269 with ksh93) exit status of
cmd1
, but it's becausecmd
was interrupted by a SIGPIPE signal whenhead -1
terminated after having read one line.To know the exit status of the elements of a pipeline
cmd1 | cmd2 | cmd3
a. with zsh:
The exit codes are provided in the pipestatus special array.
cmd1
exit code is in$pipestatus[1]
,cmd3
exit code in$pipestatus[3]
, so that$?
is always the same as$pipestatus[-1]
.b. with bash:
The exit codes are provided in the
PIPESTATUS
special array.cmd1
exit code is in${PIPESTATUS[0]}
,cmd3
exit code in${PIPESTATUS[2]}
, so that$?
is always the same as${PIPESTATUS: -1}
....
For more details see the following link.
"
set -e
" is probably the easiest way to do this. Just put that before any commands in your program.