很多時寫 Shell Script 都需要使用者確認動作, 然後詢問 yes 或者 no, Shell Script 裡面可以這樣寫:
1 2 3 4 5 6 7 8 9 |
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 或以上版本可以這樣寫:
1 2 3 4 5 6 7 |
read -r -p "Are you sure? [y/N] " response if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]] then do_something else do_something_else fi |
Bash 4.x 這樣寫:
1 2 3 |
read -r -p "Are you sure? [y/N] " response response=${response,,} # tolower if [[ $response =~ ^(yes|y)$ ]] |
Hi, 我學習您提供 BASH 4.x的方法
不管回答甚麼答案,都是執行do_something_else這邊
read -r -p “Are you sure? [y/N] ” response
response=${response,,}
if [[ $response =~ ^(yes|y)$ ]]
then
do_something
else
do_something_else
fi
Is any suggestion?