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 ==)     |      =
            |      !=         |      !=
Sign up to request clarification or add additional context in comments.

4 Comments

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 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.
Yes. It is returning me bash.
OK, then this explains the different behaviour.
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 Comment

Good one! I was looking for references and couldn't find this good one.
1

Correct Syntax for If - Else in Linux is below

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.