I have a Scenario where in I need to fetch some data by triggering another external bash file from my shell script. If I end up with any error output from external bash, My shell script should handle and should go through the fall back approach. But I am actually facing issue with that external bash file, Wherein bash returns (exit 1) in failure cases, which causes my script also to exit and never executing fall back approach. Can anyone guide how to handle the exit from external bash and run my fall back approach.
-
Are the programs and scripts that you'll run properly disciplined in the way they report errors by exiting with non-zero statuses when there's a problem. If so, it is easy to spot when something has gone wrong. If not, then it is probably simpler to fix them up so they are disciplined enough than it is to write code to analyze standard error output from the carelessly written programs — assuming that they're written carefully enough to report errors on standard error! If they don't pay attention to that either, then you're in for a world of hurt.Jonathan Leffler– Jonathan Leffler2020-01-21 03:30:25 +00:00Commented Jan 21, 2020 at 3:30
Add a comment
|
1 Answer
Not sure if this works in sh, but it works in bash. I made a try / except tool out of this, but it will work here too I believe.
#! /bin/bash
try() {
exec 2> /dev/null
#direct stderr out to /dev/null
#main block
input_function="$1"
#fallback code
catch_function="$3"
#open a sub shell
(
#tell it to exit upon encountering an error
set -e
#main block
"$@"
)
#if exit code of above is > 0, then run fallback code
if [ "$?" != 0 ]; then
$catch_function
else
#success, it ran with no errors
test
fi
#put stderr back into stdout
exec 2> /dev/tty
}
An example of using this would be:
try [function 1] except [function 2]
Function 1 would be main block of code, and 2 would be fallback function/block of code. Your first function could be:
run() {
/path/to/external/script
}
And your second can be whatever you want to fall back on. Hope this helps.
4 Comments
Jonathan Leffler
You should probably use
"$@" rather than just $@. It matters the moment one of the arguments contains white space. Unless you expect function 1 to contain arguments (1 in this case, to the function/program called function), in which case you're headed into complicated territory.MIZWOZ cpu
Good catch! I'll change my answer to reflect that.
Aditya Poluru
Thanks a lot, I will try this and let you know
chepner
There are a number of problems with this. It assumes that standard error was the terminal in the first place, and doesn't work with arbitrary "blocks of code", only simple commands with arguments. I don't see the benefit over simply writing
if function 1; then test; else function 2; fi 2> /dev/null