Archive for September, 2013

10
Sep
13

Error Handling in bash

I have never really liked error handling in bash but a few weeks back i came across the ability to use traps. this is an awesome feature and i don’t know why i have never come across it before. So the information i generally want when there is an error is:
* Error code.
* Line number of the error.
* and the command that failed.

The error code is simple we all know $? has the error of the last run command. The line number also pretty easy a quick search of the man page presents us with LINENO. the command of the failed is a bit tricky. we have BASH_COMMAND however this doesn’t give us what we want. consider the following script

#!/bin/bash
trap 'echo ${BASH_COMMAND}' err
TMP=/bla
ls -l ${TMP}

as /bla dose not exit ls will error, the trap will be sprung and the script will print out

ls -l ${TMP}

unfortunately the TMP variable has not been resolved. this is a bit annoying if the offending line is a loop. to fix this a got a bit of help from a colleague and we get something that looks pretty ugly but works

#!/bin/bash
trap 'echo $(eval echo ${BASH_COMMAND})' err
TMP=/bla
ls -l ${TMP}

So my finale header looks like this

#/bin/bash
set -e
trap 'echo "ERROR ($?) line ${LINENO}: $(eval echo ${BASH_COMMAND})' err
Advertisements