循环直到列表中的选择

时间:2017-12-29 12:19:43

标签: linux list shell loops conditional-statements

我正在尝试编写一个循环脚本,直到用户选择列表中的值(从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]

没有任何作用。总是那个错误。这是怎么回事? :(

2 个答案:

答案 0 :(得分:1)

首先,您的sale_date , sales August , 6 表明您没有使用Bash。在脚本顶部添加[[: not found,或使用#!/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 语句的好处是它们允许您使用glob模式,因此case匹配[0-9]0之间的任何数字。

如果您计划最终使用Bash,您也可以选择以下内容:

9

此处,正则表达式用于匹配从#!/bin/bash until [[ $choice =~ ^[0-9]$ ]]; do read -p "How many would you like to add? " choice done 0的数字。

答案 1 :(得分:0)

[[: not found是bash内置的,而不是sh。 你可以检查一下你的砰砰声并确定它是#!/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