有什么方法可以根据 for '循环' 检查或测试 'read' 的输入吗?
我不希望 case 语句在任何输入不正确的情况下执行。截至目前,它将循环遍历,多次输出 * ) 分支,同时仍然执行正确的输入。
例子:
echo "Select Your Options (Seperated by spaces): 1 2 3"
read SELECTION
# Test SELECTION here? Then exit if fail? IE, if a 4 is entered.
for INPUT in $SELECTION; do
case $INPUT in
1 ) echo "you selection option 1"
;;
2 ) echo "you selection option 2"
;;
3 ) echo "you selection option 3"
;;
* ) echo "Check your selection. Anything outside the following will make this fail: 1 2 3 "
RETVAL=1
exit
;;
esac
done
答案1
像这样?
rpt=0
until [ 5 -le "$((rpt+=1))" ] && unset rpt
printf '\nSelect your Options:(1|2|3): ' >&2
read SELECTION &&
case $SELECTION in
(*[!123\ ]*|*[123][123]*|'') ! :
esac
do : "${rpt?too many loops!}"
echo >&2 \
"Check your selection. Anything outside the following will make this fail: 1 2 3 "
done
for INPUT in $SELECTION
do case $INPUT in
(1) echo "you selection option 1"
;;
(2) echo "you selection option 2"
;;
(3) echo "you selection option 3"
;;
esac
done
答案2
#!/usr/bin/env bash
echo "Select Your Options (Seperated by spaces): 1 2 3"
read selection
#exit(1) unless every component of $selection is one of 1, 2, or 3
set -f #to supress glob expansion
for input in $selection; do
case "$input" in 1);; 2);; 3);; *) exit 1;; esac
done
for input in $selection; do
case "$input" in
1 ) echo "you selection option 1"
;;
2 ) echo "you selection option 2"
;;
3 ) echo "you selection option 3"
;;
esac
done