for 'loop'에 대해 '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