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

2 Answers 2

10

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 IFS= 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
  • 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.
    – FelixJN
    Sep 7, 2015 at 23:26
-1

Implementation with a simple read and break

while read release; do
 if [ "$release" == "07" ]; then
        break
 else
        echo "Is that current release? e.g: 05. Try again!"
        continue
 fi
done
1
  • 1
    This seems to reproduce exactly the kind of code that the user in the question wanted to avoid. They asked whether it was possible to move the condition of the if shatement (your "$release" == "07") into the while loop condition.
    – Kusalananda
    Sep 21, 2022 at 14:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .