Skip to content
Advertisement

If statements accepting yes or no in bash script?

I am trying to accept user input of yes or no to a question and depending on the answer read back the value of my variable. I can never get commands attached to variables to work or my if statements to accept yes or no. It just keeps going to “not a valid answer”. Please let me know how to actually get those to work in bash script. I keep lookingup different things to try and nothing seems to work. Here is what I have now:

yesdebug='echo "Will run in debug mode"'

nodebug='echo "Will not run in debug mode"'

echo "Would you like to run script in debug mode? (yes or no)"

read yesorno

if [$yesorno == 'yes']; then
        $yesdebug

elif [$yesorno == 'no']; then
        $nodebug

else
        echo "Not a valid answer."
        exit 1

fi

Advertisement

Answer

There are several problems with your code:

  1. Failure to put spaces around [ (which is a command name) and ] (which is a mandatory but functionless argument to ]).
  2. Treating the contents of a variable as a command; use functions instead.

yesdebug () { echo "Will run in debug mode"; }

nodebug () { echo "Will not run in debug mode"; }

echo "Would you like to run script in debug mode? (yes or no)"

read yesorno

if [ "$yesorno" = yes ]; then
    yesdebug

elif [ "$yesorno" = no ]; then
    nodebug
else
    echo "Not a valid answer."
    exit 1
fi
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement