Get exit status of a process in bash
You can simply do a echo $?
after executing the command/bash which will output the exit code of the program.
Every command returns an exit status (sometimes referred to as a returnstatus or exit code). A successful command returns a 0
, while an unsuccessful one returns a non-zero value that usually can be interpretedas an error code. Well-behaved UNIX
commands, programs, and utilities returna 0
exit code upon successful completion, though there are some exceptions.
echo $? # Non-zero exit status returned -- command failed to execute.echoexit 113 # Will return 113 to shell. # To verify this, type "echo $?" after script terminates.# By convention, an 'exit 0' indicates success,#+ while a non-zero exit value means an error or anomalous condition.
Alternately if you wish to identify return code for a background process/script (started with nohup
or run in background &
operator) you could get the pid of the process/script started and wait for it to terminate and then get the exit code.
$ ./foo.sh &[1] 28992 # Some random number for the process-id$ echo $! # Get process id of the background process28992 $ wait 28992 # Waits until the process determined by the number is complete[1]+ Done ./foo.sh$ echo $? # Prints the return code of the process0
More info @ http://tldp.org/LDP/abs/html/exit-status.html
You are approaching this wrong-- system() already returns the exist status: zero for success, non-zero for failure. What is likely happening is your "Test" script is written incorrectly or you are testing "status" incorrectly. I've seen the following scripting mistakes from developers.
run_some_javaecho "Done"
At no time are they tracking the exit code, the script returns the last exit code-- of the echo command. Which makes it always successful. Here are two ways of exiting correctly (and I know other coders thing some more advanced ways are better than this first one, but I don't think that's what this thread is about). Crawl, then walk, then run.
If you need the exit status, but want all the shell commands to execute.
return_code=0mv $letters $ARCHIVEreturn_code=$(($return_code + $?))mv $letters $ARCHIVEreturn_code=$(($return_code + $?))exit $return_code
If you want to exit on the failure, there is set -e
to look into, and here is another way.
mv $letters $ARCHIVE || exit 1mv $letters $ARCHIVE || exit 2