循环直到列表中的选择

问题描述 投票:-1回答:2

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


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
© www.soinside.com 2019 - 2024. All rights reserved.