0

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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Isabel
  • 25
  • 4

1 Answers1

6

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Offtopic: OP might be helped with a `debug()` function that only echoes something when `"$yesorno" == yes`. – Walter A May 26 '20 at 10:59