Created
April 27, 2015 08:17
-
-
Save yarmand/91d35b5c3fc5ce1b32f1 to your computer and use it in GitHub Desktop.
try catch in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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