Verifica a entrada antes de executar um “loop for”

2

existe alguma maneira de verificar ou testar a entrada de uma 'leitura' contra um 'loop'?

Eu não quero que a instrução case seja executada. Qualquer entrada está incorreta. A partir de agora, ele irá percorrer, emitindo o ramo *) várias vezes enquanto ainda estiver executando as entradas corretas.

Exemplo:

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
    
por Motorahead 17.12.2015 / 20:12

2 respostas

1

Assim?

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
    
por 17.12.2015 / 20:17
1
#!/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
    
por 17.12.2015 / 20:56