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

Bus*_*ted 4 shell scripting bash shell-script

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

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

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

#!/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
Run Code Online (Sandbox Code Playgroud)

Luc*_*ini 6

你为什么不使用案例?

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 
Run Code Online (Sandbox Code Playgroud)


Kus*_*nda 5

为什么不通过完全不要求用户键入区域名称来使用户的生活更轻松呢?

#!/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
        echo "Invalid choice: '$REPLY'" >&2
    else
        break
    fi
done

echo "You have chosen the '$region' region"
Run Code Online (Sandbox Code Playgroud)

如果用户从列表中输入除有效数字选项之外的任何内容,则输入的值$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
Run Code Online (Sandbox Code Playgroud)

  • @Kusalananda,相同的选择或 bash 的提示或 `read -p`。它不是您脚本的标准输出,也不是您要通过管道传输到其他内容的内容。它仅用于用户交互。如果您重定向脚本的输出,您仍然希望看到这些提示。 (2认同)