How to use user input as a while loop condition

18,812

You can't use the return code of read (it's zero if it gets valid, nonempty input), and you can't use its output (read doesn't print anything). But you can put multiple commands in the condition part of a while loop. The condition of a while loop can be as complex a command as you like.

while read -n1 -r -p "choose [y]es|[n]o" && [[ $REPLY != q ]]; do
  case $REPLY in
    y) echo "Yes";;
    n) echo "No";;
    *) echo "What?";;
  esac
done

(This exits the loop if the input is q or if an end-of-file condition is detected.)

Share:
18,812

Related videos on Youtube

razzak
Author by

razzak

Updated on September 18, 2022

Comments

  • razzak
    razzak almost 2 years

    I can do this in bash:

    while read -n1 -r -p "choose [y]es|[n]o"
    do
        if [[ $REPLY == q ]];
        then
            break;
        else
            #whatever
        fi
    done
    

    which works but seems a bit redundant, can i do something like this instead?

    while [[ `read -n1 -r -p "choose [y]es|[n]o"` != q ]]
    do
        #whatever
    done
    
  • FelixJN
    FelixJN almost 9 years
    might also just use while read REPLY ; do and add the case $REPLY in ; q) break ;; (or exit) that way REPLY is not evaluated twice.