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?

1
  • 3
    Take a look at shellcheck.net Commented Sep 7, 2014 at 7:53

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

That's the correct answer. All I need is to put $inputString into double quotes
@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.
@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.)
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

3 Comments

FYI, the ,, operator requires bash 4.
@chepner never remember what knows old and new... i have 4.3 ;) edited.
It helps when Mac OS X stays stuck on 3.2 :)
1

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

1 Comment

No it's not working the problem still exist if I write while loop like this while [ $inputString != "bye" ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.