比较 bash 中的多个选项(字符串)

比较 bash 中的多个选项(字符串)

我试图在使用read命令时仅启用某些选项,并在输入错误的可能性时退出脚本。

尝试了很多可能性(数组、变量、语法更改),但我仍然遇到了最初的问题。

如何测试用户的输入并允许\禁止运行脚本的其余部分?

#!/bin/bash

red=$(tput setaf 1)
textreset=$(tput sgr0) 

echo -n 'Please enter requested region > '
echo 'us-east-1, us-west-2, us-west-1, eu-central-1, ap-southeast-1, ap-northeast-1, ap-southeast-2, ap-northeast-2, ap-south-1, sa-east-1'
read text

if [ -n $text ] && [ "$text" != 'us-east-1' -o us-west-2 -o us-west-1 -o eu-central-1 -o ap-southeast-1 -o ap-northeast-1 -o ap-southeast-2 -o  ap-northeast-2 -o ap-south-1 -o sa-east-1 ] ; then 

echo 'Please enter the region name in its correct form, as describe above'

else

echo "you have chosen ${red} $text ${textreset} region."
AWS_REGION=$text

echo $AWS_REGION

fi

答案1

为什么不要求用户输入区域名称来让用户的生活更轻松一些呢?

#!/bin/bash

echo "Select region"

PS3="region (1-10): "

select region in "us-east-1" "us-west-2" "us-west-1" "eu-central-1" \
    "ap-southeast-1" "ap-northeast-1" "ap-southeast-2" \
    "ap-northeast-2" "ap-south-1" "sa-east-1"
do
    if [[ -z $region ]]; then
        printf 'Invalid choice: "%s"\n' "$REPLY" >&2
    else
        break
    fi
done

printf 'You have chosen the "%s" region\n' "$region"

如果用户输入的内容不是列表中的有效数字选项,则其中的值$region将为空字符串,并且我们会显示一条错误消息。如果选择有效,则循环退出。

运行它:

$ bash script.sh
Select region
1) us-east-1         4) eu-central-1     7) ap-southeast-2  10) sa-east-1
2) us-west-2         5) ap-southeast-1   8) ap-northeast-2
3) us-west-1         6) ap-northeast-1   9) ap-south-1
region (1-10): aoeu
Invalid choice: "aoeu"
region (1-10): .
Invalid choice: "."
region (1-10): -1
Invalid choice: "-1"
region (1-10): 0
Invalid choice: "0"
region (1-10): '
Invalid choice: "'"
region (1-10): 5
You have chosen the "ap-southeast-1" region

答案2

为什么不使用案例?

case $text in 
  us-east-1|us-west-2|us-west-1|eu-central-1|ap-southeast-1|etc) 
         echo "Working"
  ;;

  *)
         echo "Invalid option: $text"
  ;;
esac 

答案3

问题是这样的:

[ "$text" != 'us-east-1' -o us-west-2 -o ... ]

办法-o或者你需要一个完整的条件,所以它是

[ "$text" != 'us-east-1' -o "$text" != 'us-west-2' -o ... ]

$text看看我们每次都必须进行测试吗?

你的逻辑也是错误的;你要-a);如果不是“us-east-1”这不是“us-west-2”它不是...

所以

[ "$text" != 'us-east-1' -a "$text" != 'us-west-2' -a ... ]

还有其他方法可以进行此类测试;其中一些仅仅是“个人喜好”。然而,这种语法应该可以帮助您继续前进,并遵循原始语法的形式和结构。

答案4

你可以这样做:

valid=(foo bar doo)
echo enter something, valid values: "${valid[@]}"
read text
ok=0
for x in "${valid[@]}" ; do 
    if [ "$text" = "$x" ] ; then ok=1 ; fi ; 
done 
echo is it ok: $ok

有效值保存在 bash 数组中,该数组可用于显示和测试输入字符串。

-o除了需要完整条件这一事实之外test,还有一些观点认为不应使用

[ "$x" != "foo" -a "$x" != "bar" ] 

但反而

[ "$x" != "foo" ] && [ "$x" != "bar" ] 

相关内容