0

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

0

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

6 Comments

The quotes are necessary if $PASSWORD contains spaces.
@chepner Yes, that's what I said; it doesn't matter in this context (as in, a password with no spaces), but it does matter if you have a space, as it won't be parsed properly. I will edit to make that more clear. Note that his question was about defining VALID_PASSWORD, not testing $PASSWORD.
@GoodLooking Just curious here. What shell are you using? I think you should have at least noticed an error like [: secret: unexpected operator.
@konsolebox I am using bash. That error did popped up. I kind of ignored it. Now I know what it means. Thanks guys.
@GoodLooking But bash doesn't show that error since == is available to [ even when bash is in POSIX mode. Perhaps you're using dash instead?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.