简体   繁体   English

如果语句在 bash 脚本中接受是或否?

[英]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.我永远无法让附加到变量的命令起作用,或者我的 if 语句接受是或否。 It just keeps going to "not a valid answer".它只是继续“不是一个有效的答案”。 Please let me know how to actually get those to work in bash script.请让我知道如何真正让它们在 bash 脚本中工作。 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM