【问题标题】:how do i restart an if statement如何重新启动 if 语句
【发布时间】:2020-04-13 10:53:09
【问题描述】:

如果标题不具体,我很抱歉,但我需要一些帮助: 我正在尝试做一个小猜谜游戏,我正在尝试实现一个提示

  #!/bin/bash
echo "what comes once in a minute, twice in a moment, but never in a thousand years?
(lowercase)"
read input
if [ $input = "m" ] ; then
clear
echo "correct"
sleep 4.4
clear
elif [ $input = "hint" ] ; then
clear
echo "its a letter"   #what do i do so that after it prints "its a letter"
clear                 #it comes back to the beginning of the if statement 
else
clear
echo "incorrect"
sleep 4.4
clear
fi

例如:我运行脚本

-它将打印what comes once in a minute, twice in a moment, but never in a thousand years? -i 回复hint 并在给出提示后返回等待我输入答案

【问题讨论】:

  • 请学会缩进你的代码。
  • 使用无限循环
  • @Guack :您还应该删除第一行中#! 之前的空格。

标签: bash loops if-statement


【解决方案1】:

让它成为一个递归函数

game () {
    read -p "what comes once in a minute, twice in a moment, but never in a thousand years?
    (lowercase) " input # make read print it

    # use case instead of if\then
    case $input in
     "hint") clear; echo "its a letter"; game;;
        "m") clear; echo "correct"; sleep 4.4; game;;
          *) clear; echo "incorrect"; sleep 4.4; game;;
    esac 
}

game

【讨论】:

  • 在良好的答案后删除对game的调用。我不应该使用clear
  • 当while循环也可能(并且更容易)时避免递归。
【解决方案2】:

也许你想有更多的问题/答案,并想做类似的事情

quiz() {
   if [[ $# -ne 3 ]]; then
      echo 'Call this function like quiz "question" "hint" "answer"'
      echo "All arguments in single or double quotes."
   fi
   # Now implement something with `while` and use `break` after a good answer of give-up
   # ... your code ;-)
}

# Advanced: Store questions/hints/answers in an array and use a while loop 

set1_q='what comes once in a minute, twice in a moment, but never in a thousand years?'
set1_h='its a letter'
set1_a='m'
# set1_e for an explanation?
set2_q='Solve x in (x-a).(x-b).(x-c). ... (x-z) = x'
set2_h='Did you notice (x-x)?'
set2_a='0'

quiz "${set1_q}" "${set1_h}" "${set1_a}"
quiz "${set2_q}" "${set2_h}" "${set2_a}"

【讨论】:

  • 只是一个问题 -ne 是什么意思?
  • -ne 表示Not Equals。比较整数与字符串不同。当你使用像 [ some_test ] 这样的单个钩子时([test 的替代名称,请参阅 man test),你必须使用一些特殊的东西来进行测试,比如 less than (-lt) 或 greater equals (@ 987654331@)。在 bash 中,你有(更好!)替代 if (( $# !=3 )); then
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2015-07-22
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 2021-03-28
相关资源
最近更新 更多