LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   My If else statement only enters the first one? (https://www.linuxquestions.org/questions/linux-newbie-8/my-if-else-statement-only-enters-the-first-one-876469/)

hayloiuy 04-22-2011 04:17 AM

My If else statement only enters the first one?
 
Code:

#!/bin/bash


echo $1

if [ $1=="A" ];
       
        then echo 0 > Type.txt
else
       
        if [ $1=="B" ];
                then echo 1 > Type.txt
        else
                if [ $1=="C" ];
                        then echo 2 > Type.txt
                else
                        if [ $1=="D" ];
                               
                                then echo 3 > Type.txt
                                       
                        else
                                echo "Fail"
                        fi
                fi
        fi
fi

My code seems to always think the first if statement is true. What is wrong?

unSpawn 04-22-2011 04:30 AM

If you run the script as 'bash -vx /path/to/script.sh' you can see all variables filled in etc, etc. Also note there's no need for nesting so:
Code:

if [ "$1" = "A" ]; then
        echo 0 > Type.txt
elif [ "$1" = "B" ]; then
        echo 1 > Type.txt
elif [ "$1" = "C" ]; then
        echo 2 > Type.txt
elif [ "$1" = "D" ]; then
        echo 3 > Type.txt
else
        echo "Fail"
fi

should do and you could alternatively use a case statement:
Code:

case "$1" in
A) echo 0 > Type.txt;;
B) echo 1 > Type.txt;;
C) echo 2 > Type.txt;;
D) echo 3 > Type.txt;;
*) echo "Fail";;
esac



Code:

function help() { echo "Bash scripting guides:
http://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html
http://www.tldp.org/LDP/Bash-Beginners-Guide/html/index.html
http://www.gnu.org/software/bash/manual/html_node/index.html
http://www.grymoire.com/Unix/Sh.html
http://www.tldp.org/LDP/abs/html/
http://wooledge.org/mywiki/BashFAQ?action=show&redirect=BashFaq
http://wooledge.org/mywiki/BashPitfalls"; }


MTK358 04-22-2011 08:52 AM

Quote:

Originally Posted by hayloiuy (Post 4332385)
My code seems to always think the first if statement is true. What is wrong?

You didn't put spaces around the "=" sign.

It's not some kind of C-like expression, "[" is a command. You can put any other command after it, too.

The "[" command is basically the test command, but it requires the last argument to be "]". Read man test for more info.

http://mywiki.wooledge.org/BashPitfa..._.3D_d_.5D_.5D


All times are GMT -5. The time now is 04:18 AM.