3

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?

1
  • 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
    CommentedNov 6, 2014 at 4:32

2 Answers 2

4

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.

1
  • 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
    CommentedNov 6, 2014 at 6:34
1

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.

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.