Skip to content

Instantly share code, notes, and snippets.

@yarmand
Created April 27, 2015 08:17
Show Gist options
  • Save yarmand/91d35b5c3fc5ce1b32f1 to your computer and use it in GitHub Desktop.
Save yarmand/91d35b5c3fc5ce1b32f1 to your computer and use it in GitHub Desktop.
try catch in bash
#!/bin/bash
function try()
{
if [ -n "$CATCHED_ERROR" ] ; then return ; fi
CATCHED_ERROR=''
CATCHED_ERROR_LINE=$1
TRY_ERROR_FILE=/tmp/try_error.$$
shift
eval $* 2>$TRY_ERROR_FILE
CATCHED_ERROR=`cat $TRY_ERROR_FILE`
rm -f $TRY_ERROR_FILE
}
function catch()
{
if [ -n "$CATCHED_ERROR" ] ; then
┆ eval $*
fi
}
try $LINENO echo 'this one work'
try $LINENO ls /non_existing_path
try $LINENO echo 'should not display this'
catch 'echo "Error when listing on line $CATCHED_ERROR_LINE: $CATCHED_ERROR" >&2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment