Reputation: 407
I am trying to write a function in bash so that when any command fails, It will print a nice error message, I tried this
#!/bin/bash
msg()
{
if echo $? > 0 ; then
echo "==> Something wrong happened. Please see /var/log/install.log"
else
echo "==> Done"
fi
}
But when I tried to use them in this way:
#!/bin/bash
msg()
{
if echo $? > 0 ; then
echo "==> Something wrong happened. Please see /var/log/install.log"
else
echo "==> Done"
fi
}
mkdir vcvcxvcxv
msg
Then I ran this on terminal
$ bash check
mkdir: vcvcxvcxv: File exists
==> Something wrong happened, Please see /var/log/install.log
I got same output whatever. But I suppose to get the "Done" message when my command succeeds. Is there any help in this regard?
Upvotes: 0
Views: 777
Reputation: 189377
Although you got your immediate problem fixed already, your code isn't very idiomatic, and violates some fundamental shell scripting principles.
So the simplest fix is really
mkdir vcvcxvcxv || exit
since mkdir
already produces an error message on stderr, and exit
will propagate the value of $?
to the calling process.
Incidentally, you can get much the same effect with set -e
but it is slightly cumbersome to use for the newcomer.
If you want the "helpful" error message, perhaps this;
death () {
rc=$?
echo "$0: see /var/log/install.log" >&2
exit $rc
}
mkdir vcvcxvcxv || death
echo "$0: done." >&2
would be closer to what you really need. Notice how the status messages are redirected to standard error (and each has the name of the script, so you can see what's causing the failure when you have scripts calling scripts calling scripts, etc) and the exit status is naturally propagated to the caller, and the entire script aborted, in the case of a fatal error. Also, the flow of the main script becomes more natural as it grows;
something || death
additional thing || death
final thing || death
echo "$0: done." >&2
(Of course, if failure means death always, you actually want set -e
.)
Upvotes: 1
Reputation: 798606
This:
if echo $? > 0
does not do anything you want it to.
if [ $? -ne 0 ]
Upvotes: 3