JohnD
JohnD

Reputation: 353

Basic Shell scripting variables and if else

I am new to shell scripting and have been having issue with the following script password.sh that I copied from a tutorial.

#!/bin/sh

    VALID_PASSWORD="secret"

    echo "Please enter the password:"
    read PASSWORD

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

In my terminal, I typed ./password.sh to activate the script. When prompted for password, I input password secret but i keep getting ACCESS DENIED. What am I missing?

Also, I thought Variables does not need to be in quotations(only if there are spaces?). For example variable_1=Hello. Why in the script above, VALID_PASSWORD="secret" was in quotation?

Thank You

Upvotes: 0

Views: 144

Answers (1)

Brian Campbell
Brian Campbell

Reputation: 332856

The equality operator is =, not ==. It looks like Bash supports == as well, but other shells, like dash, do not. You may not be using Bash for your /bin/sh.

The quotes are not necessary in this context, if what you're defining to be in the variable has no spaces or other special characters. However, some people like to always use quotes, so they don't make a mistake later if they add a space and write VALID_PASSWORD=hello world, which doesn't mean what you might expect (it means run the command world with VALID_PASSWORD=hello set in its environment).

Upvotes: 1

Related Questions