Bash – Why does the exit code of a script appear to have a different value than what is returned

bashexitexit-statusshell-script

I have a script (run-docker-container.sh) that calls another script (create-docker-container.sh). create-docker-container executes a curl script against the docker remote api and returns the http code or zero if successful. The create script returns thus-wise

echo $RVAL
exit $RVAL

and in my tests has the value for $RVAL as 404, the value I'm interested in for this question.

In my run-docker-container script, I have the following lines

create-docker-container.sh $CONTAINER_NAME $CONTAINER_SETTINGS
rval=$?
echo $rval
if [ $rval -eq 404 ]; then
    ...
fi

even though create appears to be exiting with 404, the value I'm getting for $? is 148 and thus my condition handling is not being called.
Why would this be and how do I properly get the exit code from the script?

Best Answer

For historical reasons, the exit status of a process is an 8-bit number. The number that you pass to exit is reduced modulo 256 (2⁸).

Furthermore values 126 and above have a conventional meaning, indicating a failure to start the program (126 or 127) or a program that was killed by a signal (128 and above). So while you can return such values, you shouldn't unless you want to simulate these conditions.

The rule is to return 0 for success and some other value to indicate errors. This is a rule inasmuch as many tools interpret 0 as success: conditional commands such as if and while, tools that abort on errors such as shell scripts under set -e and makefiles, etc.

Regarding errors, the most common conventions are to return 1 on any error, or to return 2 on any error. The thirdmost common convention is to return 1 on an expected failure (e.g. a search command that finds nothing) and 2 on an unexpected failure (e.g. the file to search in did not exist). If you need to map HTTP error codes into exit status, you have the range 1–125 to play in (with 200 success mapping to 0), there's no standard for that.

Related Question