转到if语句的开头?

时间:2014-07-22 19:44:50

标签: bash if-statement sh

无论如何,如果用户没有在bash和sh中提供正确的输入,那么回到if语句的开头?

if [ "$INPUT" = "no" ]; then
    Do something
elif [ "$INPUT" = "yes" ]; then
    Do something else
else
    echo "Input not understood"
    Go back to beginning of if statement
fi

2 个答案:

答案 0 :(得分:3)

你必须使用一个循环; bash没有goto声明。

while true; do
  # set the value of INPUT here
  if [ "$INPUT" = "no" ]; then
    Do something
  elif [ "$INPUT" = "yes" ]; then
    Do something else
  else
    echo "Input not understood"
    continue
  fi
  break
done

在这个“无限”循环中,我们使用continue子句中的else语句返回到循环的顶部,我们在其中执行某些操作以获取{{1}的新值}。如果我们不执行INPUT子句,我们会点击退出循环的else语句。

答案 1 :(得分:2)

这称为'循环'。您在shell中有forwhile(和until)个循环。用一个。您还可以break退出循环,continue移动到下一次迭代。

在这种情况下,您不想转到if声明;你需要获得新的输入:

while read -r INPUT
do
    if [ "$INPUT" = "no" ]; then
        Do something
        break
    elif [ "$INPUT" = "yes" ]; then
        Do something else
        break
    else
        echo "Input not understood"
    fi
done