我正在尝试编写一个循环脚本,直到用户选择列表中的值(从0
到9
的单个数字)。这是我的.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]
没有任何作用。总是那个错误。这是怎么回事? :(
答案 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