tags:

views:

83

answers:

4

I'm rather new to bash scripting, and Google isn't as useful as I'd like for this. I'm just playing around with a little password entry program in my .bash_profile and have something like this:

read PASSWORD
if $PASSWORD != 'pass'; then
    echo "wrong. exiting"
    exit
fi

Unfortunately, this doesn't work. I get these errors (darwin on 10.6)...

EDIT Sorry about this posting. My browser crashed and I didn't even realize this posted. I ended up figuring it out on my own – again sorry. But thanks for the answers!

+3  A: 

Try:

read PASSWORD
if [ "x$PASSWORD" != "xpass" ] ; then
   echo "Wrong. Exiting."
   exit 1
fi
exit 0
Gonzalo
The quotes do the job that the "x" is intended for. Unless you're using an older shell that requires that trick, it's best to get away from using the "x".
Dennis Williamson
At some point I got used to add that just to make sure it worked and now it's added automatically ;-).
Gonzalo
+5  A: 

You are missing square brackets. The if line should be:

if [ $PASSWORD != 'pass' ]; then

or even better:

if [ "$PASSWORD" != 'pass' ]; then

Which will avoid failure if $PASSWORD is empty.

agateau
If you're writing Bash-specific scripts, it's good to know the differences between `[` and `[[` which provides additional capabilities. See http://mywiki.wooledge.org/BashFAQ/031
Dennis Williamson
Thanks! Both of you (and all of you!)
Isaac Hodes
+2  A: 

You might like to know about two options to the read command:

-p string

Display a prompt without a trailing newline

and

-s

Silent mode. The characters typed by the user are not echoed to the screen.

So for prompting for a password you could do:

read -sp "Please enter your password: " PASSWORD
echo

This is an excellent resource.

Dennis Williamson
Thanks for that link to Greg's Wiki!
Isaac Hodes
+2  A: 

use case/esac construct

read -p "enter: " PASSWORD
case "$PASSWORD" in
    "pass") echo "ok;;
    * ) echo "not ok";;
esac

Edit: For Dennis's qns

x=10
y=5
z=1
options=3
expression="$((x> y)) $((y> z)) $((options<=4))"
case "$expression" in
   "1 1 1")
    echo "x > y and y>z and options <=4";;
    *) echo "Not valid";;
esac
Why would you use a `case` when a simple if/then/[else] will suffice?
Dennis Williamson
because i don't want to care about comparison operators != or == or whatever.
Forgive me, but I don't understand what that means.
Dennis Williamson
ok, let me ask you back, why would i want to use if/else ? I feel comfortable using case/esac and to me, its neater.
Dennis Williamson
see my edit. And by the way, i don't use case sometimes, if that's what you are trying to tell me.
Dennis Williamson
and so and so forth... and ? what else do you want to nitpick about?
and using a variable is up to individual. I feel like it, so i will use it.