Teererai Marange
Teererai Marange

Reputation: 2132

bash if statement with strings always evaluates to true

I am getting started with bash and am having trouble with if statements. Why does the following script:

#!/bin/bash
read C
if  (( $C == 'Y' )) ; then
    echo "YES"
elif (( $C == 'N' )) ; then
    echo "NO"
fi

Seem to print YES no matter what value $C takes on.

Upvotes: 1

Views: 75

Answers (3)

chepner
chepner

Reputation: 531718

Strings inside the arithmetic statement ((...)) are recursively expanded until you either get an integer value (including 0 for an undefined parameter) or a string that causes a syntax error. Some examples:

# x expands to y, and y expands to 3
$ x=y y=3
$ (( x == 3 )) && echo true
true

$ x="foo bar"
$ (( x == 3 ))
bash: ((: foo bar: syntax error in expression (error token is "bar")

# An undefined parameter expands to 0
$ unset x
$ (( x == 0 )) && echo true
true

In your case, $C expands to some undefined parameter name, and both it and Y expand to 0, and 0 == 0.

For string comparison, use [[ ... ]] instead.

if [[ $C == Y ]]; then

Upvotes: 3

Banghua Zhao
Banghua Zhao

Reputation: 1556

Here is the right format.

#!/bin/bash
read C
if  [[ $C == 'Y' ]]
then
    echo "YES"
elif [[ $C == 'N' ]]
then
    echo "NO"
fi

Upvotes: 1

KJH
KJH

Reputation: 2450

Yep, as @larsks mentioned, you need the square brackets. Try this full version:

#!/bin/bash

read C
if [[ ${C} == 'Y' ]]; then
    echo "YES"
elif [[ ${C} == 'N' ]]; then
    echo "NO"
fi

Upvotes: 1

Related Questions