select name [in words …]; do commands; done
select 命令可以用來產生選單,底下是一個能夠自動產生兩個數字相加的練習程式,數字由 $RANDOM 產生,使用 $PS3 可以設定 select 命令的提示訊息,使用者選擇後 name 會是被選到之選項的值,而 $REPLY 是被選到之選項的代號,當使用者輸入超過選項的代號時,name 會是空字串。
範例:
#!/bin/sh
value1=$((RANDOM%100))
value2=$((RANDOM%100))
equation="$value1 + $value2"
# PS3 is the prompt message
PS3="What is the answer of ( $equation )? "
ans=$(($equation))
order=$((RANDOM%4))
# ans_list contains the items within the menu
for ((i=0; i<4; i++))
do
if [ "$i" -eq "$order" ]; then
ans_list="$ans_list $ans"
else
ans_list="$ans_list $((RANDOM%200))"
fi
done
select answer in $ans_list;
do
# answer will be empty if the selection is out of range.
if [ -n "$answer" ]; then
echo You selected the answer $REPLY\).
if [ "$(($equation))" -eq "$answer" ]; then
echo Great, \"$answer\" is correct.
break;
fi
echo \"$answer\" is incorrect.
echo Calculate again.
else
echo NOTICE: Please select between 1 to 4.
fi
done
結果:
1) 121
2) 106
3) 17
4) 128
What is the answer of ( 7 + 10 )? 1
You selected the answer 1).
"121" is incorrect.
Calculate again.
What is the answer of ( 7 + 10 )? 3
You selected the answer 3).
Great, "17" is correct.
沒有留言:
張貼留言