pxdr0
pxdr0

Reputation: 73

bash - elif statement returns same value regardless of input

I'm writing a shell script to take a number between 1 and 7 in the command line and return the corresponding day of the week. My code currently looks like this:

#!/bin/bash
echo "Please enter a number between 1 and 7 >"
read number
number=$n
if [ "$n"=="1" ]
then
echo "Monday"
elif [ "$n"=="2" ]
then
echo "Tuesday"
elif [ "$n"=="3" ]
then
echo "Wednesday"
elif [ "$n"=="4" ]
then
echo "Thursday"
elif [ "$n"=="5" ]
then
echo "Friday"
elif [ "$n"=="6" ]
then
echo "Saturday"
elif [ "$n"=="7" ]
then
echo "Sunday"
else
echo "error"
fi

this returns "Monday" regardless of the input. If I add spaces either side of the == then it returns "error" regardless of the input! I've tried various things but cannot work out why

Upvotes: 0

Views: 254

Answers (3)

Jdamian
Jdamian

Reputation: 3125

Replace the following lines of your code

read number
number=$n

with these

read number
n="$number"

update 1: the bash comparisons in the format [ "$n"=="x" ] always return the code 0 (true), no matter the x value because the test [ string ] checks whether string is NULL or not. In other words, as no blank is used, the first if sentence of your code is always true, no matter the values of variable n and the values of "x"

Upvotes: 3

user8017719
user8017719

Reputation:

An array may be simpler:

#!/bin/bash
day=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)

read -p "Please enter a number between 1 and 7 >" n
echo "${day[n-1]}"

Upvotes: 1

Mike
Mike

Reputation: 89

I saw the same thing as Jdamian but it appears to be insufficient so since you are working with number it would be prefable to work with -eq instead like this:

if [ $n -eq 1 ]; then echo "Monday"; elif [ $n -eq 2 ]; then echo "Tuesday"; elif [ $n -eq 3 ]; then echo "Wednesday"; elif [ $n -eq 4 ]; then echo "Thursday"; elif [ $n -eq 5 ]; then echo "Friday"; elif [ $n -eq 6 ]; then echo "Saturday"; elif [ $n -eq 7 ]; then echo "Sunday"; else echo "error"; fi

you can replace the ; by a new line if you don't like the one liner format

on a different note, if a mega messy if like that isn't necessary, i would suggest using a case instead for a better readability:

case $n in
    1) echo "Monday" ;;
    2) echo "Tuesday" ;;
    3) echo "Wednesday" ;;
    4) echo "Thursday" ;;
    5) echo "Friday" ;;
    6) echo "Saturday" ;;
    7) echo "Sunday" ;;
    *) echo "error" ;;
esac

Upvotes: 2

Related Questions