abhi1610 abhi1610 - 6 months ago 14
Bash Question

Error in if else statement in linux shell script

Being newbie in linux shell scripting, I had tried to implement the following code in

test.sh
:

#!/bin/sh
# This is some secure program that uses security.
clear
VALID_PASSWORD="secret" #this is our password.

echo "Please enter the password:"
read PASSWORD

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
echo "You have access!";
else
echo "ACCESS DENIED!";
fi


But while executing the script, it shows me following error:

Please enter the password:
1234
./tst1.sh: 9: [: 1234: unexpected operator
ACCESS DENIED!


I am unable to debug this error. Appreciate the much needed help.

Answer

If you are using Shell, you need to use the POSIX comparison =.

That is, use:

if [ "$PASSWORD" = "$VALID_PASSWORD" ]; then
#                ^

Instead of

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
#                ^^

You can have a good read to What is the difference between test, [ and [[ ? in order to see all the variances. Basically, if you are in Shell, use the POSIX tiny set of possibilities; if you are in Bash, you can use other things such as [[:

            |   new test [[   |   old test [
----------------------------------------------
            |      >          |      \>
string      |      <          |      \<
comparison  |   = (or ==)     |      =
            |      !=         |      !=
Comments