UNIX valid_password

596 views Asked by At

why in Cygwin Terminal - the if statement work
and ubuntu - unix - not working for
this code :

#!/bin/sh
valid_password="pass"

echo "Please enter the password:"
read password

if [ "$password" == "$valid_password" ]
then
   echo "You have access!"
else
   echo "Access denied!"
fi
2

There are 2 answers

3
emil On

because the correct syntax to [ is:

[ a = b ]

From your error message it sounds like you wrote:

if ["$password" = "$valid_password" ]

change this to:

if [ "$password" = "$valid_password" ]

notice the space after [. if just takes a shell command, try to run it and depending if the exit code from the program is 0 it will run the commands inside the if statement.

In your terminal, write i.e.:

user@localhost$ true; echo $?
0

to test your if statement:

user@localhost$ pass=pass; valid=pass
user@localhost$ if [ "$pass" = "$valid" ]; then echo 'You have access!'; fi

As @nullrevolution said, the ! is evaluated if you use double quotes, it will try to run last command in your shell history, in this case that is matching u.

user@localhost$ uname
Linux
user@localhost$ !u
uname
Linux
user@localhost$ echo "!"
sh: !: event not found

This is because the ! is evaluated before the double quotes are matched, and echo is run. If you still want to use double quotes, you will have to escape the ! outside the quotes:

echo "Access denied"\!

@nullrevolution also said you could try with bash, which has a builtin syntax for the expression inside if statements.

#!/bin/bash

valid_password=pass

echo "Please enter the password:"
read password

if [[ "$password" == "$valid_password" ]]; then
    echo 'You have access!'
else
    echo 'Access denied!'
fi

Also in your program I guess you do not want to echo the password in the terminal, to turn off echo temporary change:

read password

to

stty -echo
read password
stty echo

if you forgot to write stty echo to turn on echo again, just write reset in your terminal, and it will reset the terminal to default settings.

A useful tutorial for bourn shell script can be found here:

http://www.grymoire.com/Unix/Sh.html

2
fedorqui On

@emil pointed the answer:

if [ "$password" = "$valid_password" ]

instead of

if [ "$password" == "$valid_password" ]

Also: did you give the script executing permissions? Try

chmod +x script_name