Click to See Complete Forum and Search --> : Script: getting exit status
Sepero
01-19-2004, 05:19 PM
How do I get the exit status of a program run from script? I need something that works like this:if [ `program` ]
then
echo "program exited with 0"
else
echo "program exited with an error"
fi
jim mcnamara
01-19-2004, 06:04 PM
program
if [ $? -eq 0 ] ; then
echo "exit status is zero"
else
echo "exit status is not zero"
fi
$? is a shell variable that contains the return code from the last statement or program.
bwkaz
01-19-2004, 07:52 PM
Better yet, remove the backquotes and the brackets (you're wasting two processes):
if program ; then
echo "success"
else
echo "failure"
fi
Sepero
01-19-2004, 08:01 PM
Very much Thanks jim and bwkaz!
I didn't know that it was legal to not use brackets. :)
apeekaboo
01-23-2004, 07:25 PM
Don't forget that you can negate it as well:
if ! program; then
echo "doh"
fi
Sometimes it can be nice to use this style instead:
program && echo "worked"
or
program || echo "didn't work"
you _could_ use:
program && echo "worked" || echo "didn't work"
but this gets messy...
I especially like this when setting up a crontab:
# check every two minutes if mlnet is running, start it if not running
0-59/2 * * * * (pgrep mlnet &>/dev/null || /home/eek/bin/mldonkey-start &)
bwkaz
01-23-2004, 08:03 PM
Originally posted by Sepero
I didn't know that it was legal to not use brackets. :) Yep. Look in your /bin directory -- you should have a [ executable that points at "test".
(Actually, bash has [ and test both as builtins, but POSIX or FHS or something like that mandates that there be a /bin/[ executable.)
Anyway, the "if" command makes its decision based on the exit status of the first list (the one between "if" and the semicolon before "then"). It won't do string comparison or number comparison or anything like that, it'll only look at the exit status.
That's where test and [ come in. They do the string / number comparisons (or check for file existence, or whatever), and exit with a status appropriate for "if" to make a decision on.
So most of the time, brackets are needed (because most of the time, you need to compare things). But if the check is simple enough, they aren't.
Sepero
01-23-2004, 11:57 PM
Originally posted by apeekaboo
Sometimes it can be nice to use this style instead:
program && echo "worked" || echo "didn't work"I tried this, but it didn't work right. I think the second echo should only execute if the first echo fails(instead of if the program fails). I could be wrong.
apeekaboo
01-24-2004, 03:03 AM
Try this:
ls /foo && echo "worked" || echo "didn't work"
Unless you really have a dir called /foo this will fail.
You can then try:
echo $?
to see what exit status you get.
The program you run need to give an exit status bigger than 0 for the last part to work ($? >0).