2

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.

3 Answers 3

3

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 ==)     |      =
            |      !=         |      !=
4
  • Thank you for the answer. But I would like to ask you if you could explain it to why it is not working in shell while working on the terminal?
    – abhi1610
    Commented May 6, 2016 at 6:33
  • @abhi1610 because most probably you are working under Bash, where the if [ "$var1" == "$var" ] comparison is possible. Check your shell writing echo $0 in your console.
    – fedorqui
    Commented May 6, 2016 at 6:36
  • Yes. It is returning me bash.
    – abhi1610
    Commented May 6, 2016 at 8:02
  • OK, then this explains the different behaviour.
    – fedorqui
    Commented May 6, 2016 at 8:25
2

The comparison operator == you use to compare the two strings is a Bash extension, it doesn't exist in basic sh, which instead uses the test command which uses single = to compare strings.

1
  • 1
    Good one! I was looking for references and couldn't find this good one.
    – fedorqui
    Commented May 6, 2016 at 6:59
1

Correct Syntax for If - Else in Linux is below

if [ "$1" = "cool" ]
then
    echo "Cool Beans"
else
    echo "Not Cool Beans"
fi

Not the answer you're looking for? Browse other questions tagged or ask your own question.