LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash scripting problem with exit codes (http://www.linuxquestions.org/questions/programming-9/bash-scripting-problem-with-exit-codes-444852/)

Jeiku 05-14-2006 10:48 PM

Bash scripting problem with exit codes
 
Hi,

I'm having some problems with Bash shell scripting, here is my script:

Code:

echo "exit code: ${?} [BEFORE]"
perl ./udp_weather2.pl
echo "exit code: ${?} [AFTER]"

if [ "${?}" -ne "0" ] ; then
        echo "running again..."
        perl ./udp_weather2.pl
else
        echo "exit code is ${?}. if that's one wtf is the script doing???"
fi

The output is:

Code:

exit code: 0 [BEFORE]
time: 11:29
temperature: 0
radiation: 0
Null temp and rad values, exitting...
exit code: 1 [AFTER]
exit code is 1. if that's one wtf is the script doing???

Basically my if function is not catching the exit code of my perl script, even though the exit code is 1, it doesn't run the script again. Why is this?
My bash version:
GNU bash, version 3.00.16(2)-release (i486-slackware-linux-gnu)

Thanks for any help and I'm stumped on this one!

Jeiku

Dark_Helmet 05-14-2006 11:46 PM

Well, there are two things I'd like to mention.

The $? variable is updated after every command. So, first it reflects the exit value from the perl script. Then, after the echo, $? is the exit value of the echo command. The if-statement references the echo command's exit value. To save it, you'll need to do something like this:
Code:

#!/bin/bash

perl ./udp_weather2.pl
script_exit_value=$?
echo "exit code: ${script_exit_value} [AFTER]"

if [ "${script_exit_value}" -ne "0" ] ; then
        echo "running again..."
        perl ./udp_weather2.pl
else
        echo "exit code is ${?}. if that's one wtf is the script doing???"
fi

The other thing is that the if-statement uses a numeric comparison (-ne) but uses string arguments. It might work, but it's a little unusual.

Jeiku 05-15-2006 01:22 AM

Cool, thanks! I didn't realise that $? is updated after every command... doh! :)


All times are GMT -5. The time now is 02:56 PM.