Don P
Don P

Reputation: 63567

Unix: If/then statement is always false

This if/then statement in Unix always puts me in the else statement. I am using Bash.

name="Don"
if [ "$name" == "Don" ]; then
  echo "Hi Don!"
else 
  echo "You are not Don. You are: $name"
fi

This is my first Unix shell script, so I'm sure it's something obvious. I've checked against the style guide and other if/then examples, but don't see anything wrong: http://www.dreamsyssoft.com/unix-shell-scripting/ifelse-tutorial.php.

Upvotes: 2

Views: 614

Answers (3)

Yvonne B
Yvonne B

Reputation: 21

There was only one thing wrong in your original code: the line that reads

echo "Hi Don!"

The shell is trying to interpret the special character ! Try putting this line single quotes example:

echo 'Hi Don!'

Upvotes: 0

Sebastian Büttner
Sebastian Büttner

Reputation: 351

I executed your script and it jus tworked as expected.

If this it the full code snipped, did you propably forget to call the bash? I am asking this because when executing the snipped with "sh", it behaves exectly as you said as this is just partial valid for sh.

So I think you missed this:

#!/bin/bash
name="Don"
if [ "$name" == "Don" ]; then
  echo "Hi Don!"
else 
  echo "You are not Don. You are: $name"
fi

Upvotes: 3

konsolebox
konsolebox

Reputation: 75458

If you're in a POSIX shell don't use ==. Instead use =. == is specific to Bash.

name="Don"
if [ "$name" = "Don" ]; then
  echo "Hi Don!"
else 
  echo "You are not Don. You are: $name"
fi

Upvotes: 4

Related Questions