Code Snippets : BASH : Run command monitoring process return codes

This is handy if you deal with 'glue' scripts. I have to deal with scripts, that bring up systems like databases, mq ..etc, and do some work. The scripts contain large number of shell commands, and debugging the whole script when something goes wrong can be tedious. Most of the time the error is caused by some other error that happened a few lines ago.

What I wanted ws a small 'wrapper' function to execute shell commands, monitoring their return values, and terminiating the execution when an 'unsuccessfull' return code is returned. Shell scripts return zero when successfull, and non-zero values when not. So it makes sense to terminate the script where the error occurs.

You can use
set -e
to do the same.

When '-e' is set, bash will terminiate at the first error of the script.

#!/bin/bash
set -e
command_1
command_2

 

Pretty simple, right, but some of the commands 'may' fail. For example, trying to start a database that is already running will return a failure code. But this error can be ingored. With 'set -e' this sort of selective ignoring is not simple, of course you can do something like this


#!/bin/bash
set -e  # turn on return code checking
command_1
set +e   # turn off return code checking
command_2
set -e   # turn on checking again
command_3
command_4

 

yeah it works, but I needed a 'wrapper' to selectively execute commands, and here is the script that does it

For BASH to handle SPACES correclty (ls -la or cp '/tmp/a b c') we need to wrap the arguments in quotes,

"$@"

Download code here

#!/bin/sh

# runs a command and terminates if the exit code is non-zero
function run_command ()
{

    "$@"
    retcode=$?
    if [ "$retcode" -ne 0 ]
    then
        echo "run_command : following command failed with non-zero return code ($retcode)... exiting"
        # the echo may not print 'quots' correctly, but the program is executing with right quotes
        echo  "$@"
        exit -1;
    fi
} 


## Main

run_command "$@"