Reputation: 6354
I was playing with bash programming. I have written a simple bash program which takes input from reader. If reader typed the string "bye" the while loop ends. So the program is pretty simple I have written 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 perfectly until user type two words at a time.
If user type something like this
bye bye
Program crashes giving the following error
./WhileLoop.sh: 5: [: bye: unexpected operator
How can i modify the code so that program can take multiple input?
Upvotes: 3
Views: 2079
Reputation: 9285
Put double quotes around inputString
in while
's condition. Without double quotes, if your variable is empty, it will raise a error.
Update:
There's a typo on script, add $
before inputString
, make variable substitution: while [ "$inputString" != "bye" ]
Upvotes: 3
Reputation: 63974
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
Upvotes: 2
Reputation: 15776
Use a $ in front of a variable to have it expanded. $inputString
Upvotes: 1