Shell – how to detect if command execute failed in shell

exit-statusshell-script

I use Java to call a shell script in remote machine.

I want to know if the shell execute failed. But I found that, checking the return code $? after the script is finished doesn't work. $? only indicate the last command's result code in the script.

So even a command execute failed, but the last command execute success. I can't find it. I want to know how to solve the problem?

Need I check the result code for every command in shell? And if one command execute failed, exit the script?

Best Answer

You can use set -e inside the script, or pass -e to the interpreter when launching.

#!/bin/sh
set -e

or

/bin/sh -e /path/to/script.sh

 

http://pubs.opengroup.org/onlinepubs/007904975/utilities/set.html:

-e

When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

Related Question