Made a nice little try() function today for simplifying checking/dealing with return codes from commands. It uses the function text() I posted earlier to colorfy output: How to easily add colored text output in bash scripts. The function accepts 2 parameters, how it should behave if a problem occurs and the command to be executed: try <silent|warn|fatal> command
silent: save the return status in the global variable command_status
warn: if the command has a return code > 0, print a warning and save the return status in the global variable command_status
fatal: if the command has a return code > 0, print an error and exit
Obviously not as versatile as a python try/except, bu streamlines verifying the command return codes.
Example Usage:
1
2
|
try warn false
try fatal ls -al doesnotexist
|
Output
Warning: ‘false‘ failed with return code –1–
ls: cannot access doesnotexist: No such file or directory
Error: ‘ls -al doesnotexist‘ failed with return code –2–
File: error_handling.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
command_status=
function try() { #{{{
if [ "$#" = "0" ]
then # not enough parameters were provided
echo "ERROR: sytnax is 'try <silent|warn|fatal> command'"
exit 1
fi
local returncode=0
local severity=${1}
shift
local cmd="${@}"
$cmd
returncode=$?
if [[ ${returncode} -gt 0 ]]
then
case ${severity} in
silent )
command_status=${returncode}
;;
warn )
printf "%s: '%s' failed with return code -%s-\n" $(text yellow "Warning") "$(text blue "${cmd}")" $(text yellow "${returncode}")
command_status=${returncode}
;;
fatal )
printf "%s: '%s' failed with return code -%s-\n" $(text red "Error") "$(text blue "${cmd}")" $(text yellow "${returncode}")
exit ${returncode}
;;
* )
printf "%s: Wrong usage of the try() function\n" $(text red "Error")
exit 1
;;
esac
fi
} #}}}
|