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?

  • have you considered having the remote script create a log file? After execution, you'll be able to return exit value based on scanning the exit log (e.g. 1 for error phrase is log file). By convention $? returns the exit status of the last command executed in a script or in a function. Exit status.
    – Simply_Me
    Nov 6, 2014 at 4:32

2 Answers 2


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

set -e


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




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.

  • 1
    It's OK, but I have a grep operation in my shell, and the script exit when the grep failed. The if statement if [ echo $line | grep -q "$field" ] ; then seems doesn't work.
    – NingLee
    Nov 6, 2014 at 6:34

You can also use the trap.

trap 'command' signal

Your shell script may like this:

trap 'trapHandler $LINENO' ERR

to catch the ERR signal. trapHandler() can be like this.

    echo "[LINE:$1] Error:exited with status $retCode"
    exit $retCode
  • 1
    @NingLee For your question, just if echo $line | grep -q "$field" the check it.
    – shangyin
    Nov 6, 2014 at 6:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .