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