Bash Until the loop ends
I have been playing around with bash programming. I wrote a simple bash program that takes input from the reader. If the reader has typed the string "bye", the while loop ends. So the program is pretty simple, I wrote something like this
#!/bin/sh
inputString="hello"
while [ inputString != "bye" ]
do
echo "Please write something (bye to quit)"
read inputString
echo "You typed : ${inputString}"
done
It works great as long as the user doesn't enter two words at a time.
If the user enters something like this
bye bye
A program crash causing the following error:
./WhileLoop.sh: 5: [: bye: unexpected operator
How can I change the code so that the program can accept multiple inputs?
+3
source to share
3 answers
In bash
4+ you can also:
while read -r -p 'Please write something (bye to quit)>' ans
do
echo "your answer =$ans="
#convert the $ans to lowercase to match "BYE"
#use matching to match "bye bye" or "byeanythinghere"
#in case of double [[ don't needed the "", but never harm, so using it
[[ "${ans,,}" =~ bye.* ]] && exit 0
#[[ ${ans,,} =~ bye.* ]] && exit 0 #works too
echo "not bye - yet"
done
+2
source to share