bashif-statement

how to use if condition in linux


echo "Enter a grade"
read grade
if test $grade="A"
then
  basic=6000
elif test $grade="B"
then
  basic=5000
else
  basic=4000
fi
echo "Your basic is $basic"

When I execute this code in terminal with any grade it always returns "Your basic is 6000". what is the mistake in this code?


Solution

  • You need to put a space around the =. As it is now, you just give the test command one argument, which is $grade="A", since space separates arguments. If you put spaces around =, then test will have 3 arguments, i.e. (an expanded) $grade, = and "A".

    It's also best practice to quote variable expansions to ensure empty values, whitespace, and other special characters are handled correctly.

    Thus:

    echo "Enter a grade"
    read grade
    if test "$grade" = "A"
    then
      basic=6000
    elif test "$grade" = "B"
    then
      basic=5000
    else
      basic=4000
    fi
    echo "Your basic is $basic"