Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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|improve this answer
    
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 at 23:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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