Veer Shrivastav
Veer Shrivastav

Reputation: 5496

Unix - if else EOF error

I am writing the following code:

if [ $opt -ge $max -o $opt -le  0 ]
then
    echo "Bad";
else
    echo "Good";
    if [ $opt = "\" -o $opt = "/"  ]
    then
        echo "Good";
    else
        echo "Invlaid"; //Line number 21
    fi
fi //Line number 23 no Line number 24.

this shows an error:

./file.sh: line 21: unexpected EOF while looking for matching `"'
./file.sh: line 24: syntax error: unexpected end of file

If I place this code:

if [ $opt -ge $max -o $opt -le  0 ]
then
    echo "Bad";
else
    echo "Good";
fi //Line number 23 no Line number 24.

Then there is no error. I am not able to figure out the problem.

Upvotes: 0

Views: 286

Answers (3)

Mandar Pande
Mandar Pande

Reputation: 12984

opt="\\"

echo $opt
\

if [ $opt = "/" -o $opt = "\\" ]; then echo "Hi"; else echo "bye"; fi
Hi

Upvotes: 0

anubhava
anubhava

Reputation: 785531

Backslash \ inside double quotes needs to be escaped or else you can use single quotes like this:

if [ $opt = '\' -o $opt = '/' ]; then
   echo "Good"
fi

Single quotes treat the wrapped string literally that's the precise reason single quote in shell cannot be escaped.

Upvotes: 1

Joni
Joni

Reputation: 111339

Where you write "\" you start a string literal whose first character is a double quote. To include a back slash in a string you have to precede it with another:

"\\"

Upvotes: 3

Related Questions