3

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?

mirmdasif
  • 6,014
  • 2
  • 22
  • 28

3 Answers3

3

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" ]

Zulu
  • 8,765
  • 9
  • 49
  • 56
  • 1
    That's the correct answer. All I need is to put $inputString into double quotes – mirmdasif Sep 07 '14 at 07:45
  • 2
    @sadasidha No, this ISN'T the correct answer. The quoted `"inputString"` isn't the same as the quoted `"$inputString"`. So, yes, need to quote, but need to put the `$` in the front. Please, MARK only really correct answers. – clt60 Sep 07 '14 at 12:46
  • @jm666 I assume the lack of a `$` is a typo in the question, because the posted code would not produce the given error. (It would simply loop forever because the two literal strings would never equal each other.) – chepner Sep 07 '14 at 14:12
2

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
clt60
  • 62,119
  • 17
  • 107
  • 194
1

Use a $ in front of a variable to have it expanded. $inputString

Austin Phillips
  • 15,228
  • 2
  • 51
  • 50
  • No it's not working the problem still exist if I write while loop like this while [ $inputString != "bye" ] – mirmdasif Sep 07 '14 at 07:28