4

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
8

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.)

  • 1
    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. – Fiximan Sep 7 '15 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.