Reputation: 1456
In a bash script that utilizes other commands, I understand that I can capture the return code of said commands by using $?
. While this method lets me know in general if the command succeeded 0
, or failed !0
, it does not provide me more details in scenarios where the command may only have two exit codes being 1
and 0
.
For example:
If I am using the reposync
command in linux, I may have the command succeed and return 0
, but in the event that it fails due to a disconnected network it will return 1
despite stdout
returning more errors:
[<reponame>: <repo_number> of <total_repos> ] Downloading <package>
Could not retrieve package <package> Error was failure: getPackage/<package>: [Errno 256] No more mirrors to try.
Similarly it will also return 1
if a package was removed due to a failed GPG signature verification (assuming that the --gpgcheck
flag was used).
So my question is: From a bash script, how should I conduct error handling on commands with binary exit codes?
Initially my thought would be to redirect the error output to a string to handle the error messages accordingly:
ERRORS=$( reposync 2>&1)
Unfortunately, this just captures the message and doesnt allow me to conduct any additional error handling behavior besides reporting. Would grepping through this error message really be the cleanest way to handle this scenario?
Upvotes: 1
Views: 159
Reputation: 2154
Assuming that you have your error text in the variable ERRORS
, you could use case
to check for certain simple cases like this:
case "$ERRORS" in
*<string>*)
# Code for error that contains <string>
;;
*<string2>*)
# Code for error that contains <string2>
;;
*)
# None matched
;;
esac
The case
instruction (see bash) will let you use patterns. For example *
will match anything; a|b
will match a
or b
and so on.
That may be enough for simple checks.
In the example you mention, you may also try to capture the error code within the text, [Errno 256]
. For that you may use a perl
one-liner like:
echo $ERRORS | perl -n -e'/\[Errno\s*(\d+)\]/ && print $1'
Which you may combine with a case
statement.
Upvotes: 1