Need of store the return code in shell script.

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 --
[ -z $AMBIENTE ] && export AMBIENTE=depwiz
so_initcode() {
echo 0 > $fret
so_retcode() {
[ -f $fret ] && retcode=$(cat $fret)
[ -z $retcode ] && retcode=0;
return $retcode;
so_setcode() {
[ -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)"
#-- source of --

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):

#-- source of --
ls 2>/dev/null 1>/dev/null          # success here.
ls /root/* 2>/dev/null 1>/dev/null  # error here.
uxhfuihuf                           # error here.
ls 2>/dev/null 1>/dev/null          # success here.
echo ret is: $?
#-- source of --

This gave me an output like that:

[mulatinho@work:~] ./
{*} retCode: 0, statusCode: 0
{*} retCode: 2, statusCode: 2
./ 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  ! 😀


Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do

Você está comentando utilizando sua conta Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: