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.)
Related videos on Youtube
![razzak](https://i.stack.imgur.com/6VPpQ.jpg?s=256&g=1)
Author by
razzak
Updated on September 18, 2022Comments
-
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 almost 9 yearsmight also just use
while read REPLY ; do
and add thecase $REPLY in ; q) break ;;
(orexit
) that wayREPLY
is not evaluated twice.