これらはHamish's answerのよりコンパクトで用途の広い形式です。大文字と小文字の混合を処理します。
read -r -p "Are you sure? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
do_something
;;
*)
do_something_else
;;
esac
または、Bash >= バージョン 3.2 の場合:
read -r -p "Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
do_something
else
do_something_else
fi
注:$response
が空の文字列の場合、エラーが発生します。修正するには、引用符を追加するだけです: "$response"
. – 文字列を含む変数では常に二重引用符を使用します (例:"$@"
代わりに使用することをお勧めします$@
)。
または、Bash 4.x:
read -r -p "Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ "$response" =~ ^(yes|y)$ ]]
...
編集:
あなたの編集に応じてconfirm
、私の回答の最初のバージョンに基づいてコマンドを作成して使用する方法を次に示します (他の 2 つと同様に機能します)。
confirm() {
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
この機能を使用するには:
confirm && hg push ssh://..
また
confirm "Would you really like to do a push?" && hg push ssh://..