Bash (Ubuntu) – Strings in while loops?

I am trying to create a while loop in bash that won’t continue until the user enters the word “next”. I can’t seem to figure out how to use strings for the condition though.

#Beginning of code
echo -e "Please type next to continue."
read word 
while [ "$word" -ne "next" ]
do 
    read word
done
#the rest of the code
Asked By: RootFAIL

||

Use != instead of -ne

echo -e "Please type next to continue."
read word 
while [ "$word" != "next" ]
do 
    read word
done

Check this for comparison operators.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html

Answered By: bluefoggy

You are using the wrong comparison operator. You should use “!=” for string and “-ne” for integers as follows:

#Beginning of code
echo -e "Please type next to continue."
read word
while [ "$word" != "next" ]
do
    read word
done
#the rest of the code

Checkout this page: Advanced bash Scripting: Comparison Operations

Answered By: dgsleeps

As others have stated you should not use the -ne integer comparison to compare strings – rather you should use =/!= in test [ brackets ]. Still though, even that is brittle at best – the strings must match exactly, and '' does equal ''. It is often better to handle cases in that context:

set --
while   read  word
        case $?$#$word            in 
        ($?$#[Nn][Ee][Xx][Tt]) ! :;;
        ([!0]*|05*) ! break       ;;esac
do      set '' "$@"
done   

Provided a default value for $IFS (which is worth looking into if you plan to do shell reads), that should work for any upper/lower value of next (if you require it) and keep the loop from running away without end.

Answered By: mikeserv

I think you want:

echo 'Please type "next" to continue.'
while read word && [ "$word" != next ]; do
  : something in the loop if needed
done

It’s a good idea to also check for end-of-file on stdin (here by checking the exit status of read).

Answered By: Stéphane Chazelas
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.