the $? variable

my encounter with this variable hasn’t been very pleasant i’ve been trying to debug a snippet of shell script similar to this:

#!/bin/bash
Test()
{
var=3
return $var
}
Test2()
{
Test
print this is the return value $?
print this is the return value again $?
}
#it all starts here
Test

The output would then be:
this is the return value 3
this is the return value again 0

Instead of a 3 and 3 which is what I was expecting. It took a while to find this out.  The actual snippet was this:

select_server_root_folder()
{
choice=’server’

#display a menu
echo “select root folder to restore”
echo “”
echo “4. main menu”

read ans grbg
case $ans in
1)      folder=’usr’;;
2)      folder=’etc’;;
3)      folder=’var’;;
4)      main_menu;;
esac

#return value of function will be either 0 or 1
select_incremental_or_full $choice $folder
#echo below was used for testing to see if the value being returned by above function was either 1 or 0
#return value was just as expected/chosen.
echo return value is $?
#the condition statements below were working, at least i thought they were because i’ve only been testing the 1st #if statement below. as it turns out the value of $? resets to 0 which would be its default  after it’s used. i guess that’s the term for it.
if [ $? -eq 0 ]
then
do stuff here
fi
if [ $? -eq 1 ]
then
do other stuff here
fi
#this echo statement is where I was able to determine that you can only use the variable $? which holds the #return value of a function. it was always displaying 0 and 0 only
echo $?

}

to overcome the shortcoming of the script, i have set the value of the variable $? to another (var=$?) and used that variable instead.

note to self: good times ;]

note#2: found

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Security Code:

This site uses Akismet to reduce spam. Learn how your comment data is processed.