【问题标题】:Loop until choice within list循环直到列表中的选择
【发布时间】:2018-06-09 21:22:47
【问题描述】:

我正在尝试编写一个循环的脚本,直到用户在列表中选择一个值(从09 的单个数字)。这是我的 .sh 脚本,我尝试使用 sh 命令在 ubuntu 16.04 shell 中运行:

choice=999
echo $choice
until [[ $choice in 0 1 2 3 4 5 6 7 8 9 ]]
do
  read -p "How many would you like to add? " choice
done

无论我做什么,我都无法让它发挥作用。这是一个测试,让您了解手头的错误:

sh test2.sh
999
test2.sh: 3: test2.sh: [[: not found
How many would you like to add? f
test2.sh: 3: test2.sh: [[: not found
How many would you like to add? 2
test2.sh: 3: test2.sh: [[: not found
How many would you like to add? 3
test2.sh: 3: test2.sh: [[: not found
How many would you like to add? r
test2.sh: 3: test2.sh: [[: not found

我尝试了很多东西:

  • 避免使用until 并使用while
  • 只使用单数方括号[ condition ],或者根本不使用方括号
  • 使用=~匹配正则表达式^[0-9]

没有任何作用。总是同样的错误。这是怎么回事? :(

【问题讨论】:

    标签: linux list shell loops conditional-statements


    【解决方案1】:

    首先,您的[[: not found 表明您没有使用 Bash。在脚本顶部添加#!/bin/bash,或者使用bash test2.sh 运行它,或者使用标准的[

    不管怎样,你不能这样使用in。一种替代方法是使用case 声明:

    while :; do
      read -p "How many would you like to add? " choice
      case $choice in
        [0-9])
          break
          ;;
      esac
    done
    

    case 语句的好处在于它们允许您使用 glob 模式,因此 [0-9] 匹配从 09 的任何数字。

    如果你最终打算使用 Bash,你也可以这样做:

    #!/bin/bash
    
    until [[ $choice =~ ^[0-9]$ ]]; do
      read -p "How many would you like to add? " choice
    done
    

    这里,正则表达式用于匹配从09 的起始数字。

    【讨论】:

    • 谢谢,我试过第二种方法,效果很好。
    • 不客气,我还编辑了您的问题,以便更清楚地说明您最初想要做什么。如果您不同意,请随时重新编辑。
    【解决方案2】:

    [[: not found 是内置的 bash,而不是 sh。 你能检查你的she-bang并确定它是#!/binb/bash,而不是#!/bin/sh吗?第二,以bash scriptname.sh 运行脚本,而不是sh

    最后,尝试像这样重写你的脚本:

    choice=999
    echo $choice
    while [[ "$(seq 0 9)" =~ "${choice}" ]]
    do
      read -p "How many would you like to add? " choice
      # ((choice++)) If choice=999, script will not read anything. 
      # If 0 <= choice <= 9, script will not never stopped.
      # So, you should uncomment ((choice++)) to stop script running when choice become
      # more than 9.
    done
    

    【讨论】:

    • 看起来脚本正在使用sh 运行(见顶行),虽然这不是唯一的问题:)
    • @TomFenech 错过了它,但 sh 也可以是 bash 的符号链接。因此,请尝试在 bash scriptname.sh 上首先运行脚本,检查 she-bang。在那之后,我们会修正你的语法:)
    • bash test2.sh 99 test2.sh:第 3 行:条件二元运算符预期 test2.sh:第 3 行:in' test2.sh: line 3: until [[ $choice in 0 1 2 3 4 5 6 附近的语法错误7 8 9 ]]'
    • 好的,等一下'我会正确地重写你的脚本。
    • @Alexander 还检查了 Tom Fenech 的回答。我认为这更接近你的情况。
    猜你喜欢
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2015-07-03
    • 2014-12-07
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多