LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Strange if statement behaviour when using bash/bash script (https://www.linuxquestions.org/questions/programming-9/strange-if-statement-behaviour-when-using-bash-bash-script-659722/)

freeindy 08-01-2008 07:05 AM

Strange if statement behaviour when using bash/bash script
 
Hi,

I have a strange behaviour I don't seem to understand.

Bash version is:
Code:

$ bash --version
GNU bash, version 3.00.15(1)-release (i686-redhat-linux-gnu)
Copyright (C) 2004 Free Software Foundation, Inc.

In my prompt i do the following:
Code:

]$ echo $?
1
$ if [ $? -eq 1 ] ; then
> echo good
> else
> echo bummer
> fi
good

So far so good. Logic seem right, BUT in my script whre I have exactly the same code:
Code:

echo $?
if [ $? -eq 1 ] ; then
  echo good
else
  echo bummer
fi

I get:
Code:

$./do
1
bummer

If I change the logic in my script (Completely the opposite):
Code:

echo $?
if [ $? -ne 1 ] ; then
  echo good
else
  echo bummer
fi

I get:
Code:

1
good

Now, for me this is very odd. Am I missing something?

Thanks,
Indy

burschik 08-01-2008 07:38 AM

Code:

# ls no_such_file
# echo $?
> 1
# echo $?
> 0


colucix 08-01-2008 07:42 AM

Code:

line 0:  some_failed_command
line 1:  echo $?
line 2:  if [ $? -eq 1 ] ; then

The $? special variable is the exit status of the last executed command. In line 1 the exit status is from a previous command in line 0. But in line 2 it is the exit status of the command in line 1. If the echo command is successfull, as in your examples, the $? variable is updated to its exit status, that is 0.

AnanthaP 08-01-2008 07:46 AM

I think you want $* not $?

freeindy 08-01-2008 08:55 AM

oh yeah that's right.

But still, it doesn't change if i change the code to:
Code:

retval=$?
echo $retval
if [ $retval -ne 1 ] ; then
  echo good
else
  echo bummer
fi

And the output still confuses me:
Code:

1
bummer

AnanthaP: No, I want $? because I'm evaluating a return from a funtion

colucix 08-01-2008 09:30 AM

Code:

if [ $retval -ne 1 ] ; then
  echo good
else
  echo bummer
fi

You used "not equal". The output must be "bummer".

freeindy 08-04-2008 02:49 AM

oh my, would you believe it.
Thanks colucix. Ofcourse it must be bummer. I guess i was too tired to think.

Indy

jlinkels 08-04-2008 06:00 AM

I copied your first script, and it was working as expected by you. I wonder if you posted the complete script or only this fragment.

Anyway, in cases like this run your script with:
Code:

sh -x yourscript.sh
Indispensable to show the flow within questionable tests cases.

jlinkels


All times are GMT -5. The time now is 08:51 AM.