Reputation: 743
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.
Upvotes: 2
Views: 1420
Reputation: 289625
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 ==) | =
| != | !=
Upvotes: 3
Reputation: 195
Correct Syntax for If - Else in Linux is below
if [ "$1" = "cool" ]
then
echo "Cool Beans"
else
echo "Not Cool Beans"
fi
Upvotes: 1
Reputation: 409166
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.
Upvotes: 2