LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   If .. then... else .. fi (https://www.linuxquestions.org/questions/linux-newbie-8/if-then-else-fi-830311/)

jv2112 09-04-2010 08:23 AM

If .. then... else .. fi
 
I am trying to learn if , then , else statements and I can't get it correct. I have written a basic script below and from what I am reading it looks correct but it does not go to the second option (else) if the first argument is not true.

Any help would be appreciated.:newbie:

Quote:

#! /bin/bash

echo "Do you want to enter the pit ?"
read answer

if [ $answer=yes ]; then

echo " Good Luck !"
else
echo " Chicken ....."
fi




PS -> This is not homework question. (Kinda sounds like one) Not even in school. Just trying to learn...:study:

jay73 09-04-2010 08:31 AM

if [ $answer = yes ]

You need the spaces to make a valid comparison.

Note: you may want to use == instead of =. It helps to avoid that sort of confusion.

jv2112 09-04-2010 09:06 AM

Thanks !!!
 
:hattip:

white space = Root of all evil :doh:

Thanks for the help.

grail 09-04-2010 09:31 AM

Please mark as SOLVED if you have a solution.

colucix 09-04-2010 09:44 AM

Even better in bash and ksh you might use the extended test command, with double square brackets. Among other advantages, it prevents logic errors when the value of the variable is null and you missed the double quotes around it. Example:
Code:

if [[ $answer == yes ]]
then
  echo something
fi

For a discussion about the extended test command, you can take a look at the Advanced Bash Scripting Guide, here.

slakmagik 09-04-2010 01:47 PM

Quote:

Originally Posted by jay73 (Post 4087862)
if [ $answer = yes ]

You need the spaces to make a valid comparison.

Note: you may want to use == instead of =. It helps to avoid that sort of confusion.

In some shells that will produce something along the lines of '[: ==: unexpected operator'. Generally, tests should be written '[ foo = bar ]' or (better), if the shell is capable, as colucix says, '[[ foo == bar ]]'.

jay73 09-04-2010 04:15 PM

No doubt. But even the "echo" command is not as portable as many seem to assume; for maximum portability C-like printf should be used...


All times are GMT -5. The time now is 05:07 PM.