So here I am again posting about shell script, in these days I was needing store the return code of an script in multiple places and then in the final of this shell show the status of these return codes.

So basically I was needing check every command or sub-script that was running  in the main code, as far we know every time that one command or script are executed the value of ‘$?’ is changed, so if I run an command that return different of zero (fail) and then some thing that return zero (success) and check the return code in the last line I will never know that in the final of script something went wrong.

So I decided to make something to store the value of all commands that are executed with one particularity, when there one error in script I store the error in a place and then I explicity show the error in the final of log. The result of this script follow bellow:#– source of retStore.sh –

#!/bin/bash
[ -z $AMBIENTE ] && export AMBIENTE=depwiz
fret=/tmp/depwiz.${AMBIENTE}.ret
so_initcode() {
	echo 0 > $fret
}
so_retcode() {
	[ -f $fret ] && retcode=$(cat $fret)
	[ -z $retcode ] && retcode=0;
	return $retcode;
}
so_setcode() {
	retnew=$?
	[ -f $fret ] && retcode=$(cat $fret)
	[ -z $retcode ] && retcode=0 && echo $retnew > $fret
	[ $retcode -eq 0 -a $retnew -ne 0 ] && echo $retnew > $fret
	echo "{*} retCode: $retnew, statusCode: $(cat $fret)"
}

Now when I try to execute a large script and need to catch all errors I use something like that (only an simple example of an script):

#!/bin/bash
source retStore.sh
so_initcode
ls 2>/dev/null 1>/dev/null          # success here.
so_setcode
ls /root/* 2>/dev/null 1>/dev/null  # error here.
so_setcode
uxhfuihuf                           # error here.
so_setcode
ls 2>/dev/null 1>/dev/null          # success here.
so_setcode
so_retcode
echo ret is: $?

This gave me an output like that:

[mulatinho@work:~] ./simpleScript.sh
{*} retCode: 0, statusCode: 0
{*} retCode: 2, statusCode: 2
./simpleScript.sh: line 30: uxhfuihuf: command not found
{*} retCode: 127, statusCode: 2
{*} retCode: 0, statusCode: 2
ret is: 2

Now everything is cool and the errors are caught  ! :D