Reputation: 2934
Ok so I saw at work a script which is on OpenVMS using the DCL scripting language that they have a way to do a catch all for warnings or errors etc...
There is a page about it here. http://h71000.www7.hp.com/doc/84final/9996/9996pro_150.html basically its ON warning THEN GOTO sendfailemail
or something like that. I was wondering without using a bunch of if statements is there a way to do such a thing in bash?
I am looking for something that can do a trap not just based on ERR but return code. What is nice about vms is that you can do on warning which on vms is exit status 0 vs error which is exit status 2. So I know I can do trap ... ERR but I wanted something that could trap exit status 1 or 2 specifically.
Upvotes: 2
Views: 2174
Reputation: 299345
Just to be clear about the "normal" thing to do:
set -e
trap 'echo "Failed"' ERR
echo "Start"
false
echo "End"
In this example, the set -e
will cause the script to exit if anything returns non-0 (after running the ERR
trap). In unix, non-0 means "error." There is no return value for "warning." So if you go creating special return values for your scripts, you're not going to fit into unix command pipelines correctly. You really, really need to return 0 on success, and anything else should be some kind of failure.
That said, let's say there's some really great reason here, and you have an ecosystem of scripts that have special return values. You can certain do this. Just trap ERR
and check $?
(note that I've removed set -e
since here you exit
manually):
trap 'if [ $? == 2 ]; then echo "Failed"; exit 2; fi' ERR
echo "Start"
false
echo "End"
This won't fail, since false
returns 1.
If you need this only in a few places and want to be explicit, you can create your own wrapper functions to manage it without too much extra coding.
function run() {
$*
if [ $? == 2 ]; then
echo "Failure"
exit 2
fi
}
run echo Start
run true
run false
run echo "End"
Upvotes: 3
Reputation: 10653
Simple:
if yourcommandhere; then
echo 'No error'
else
echo "Error! Exit status of the last command is $?"
fi
Upvotes: -2