superuserdo
superuserdo

Reputation: 1657

Bash if else string variable comparison

I am writing a shell script at which I am trying to compare 2 variables that are strings. Every thing works fine as in all the variables have a value from the commands however my if then else statement is not working.

#!/bin/bash

name=$1

for i in {1...10} 

do        
username=sudo cat /class/rolls/CSCE215-*|awk 'BEGIN {FIELDWIDTHS = "32 20"} {print $2}'|cut -d " " -f6 |sed -n '1,1p'

if ["$name" == "$username"] 
then  
echo Correct Username
else
echo Incorrect Username
fi  

done

All of the tutorials and help online appears to have what I have here but I cannot find out what is wrong with mine.

Upvotes: 0

Views: 3310

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84521

When using test or [, the correct comparison is:

test "$string1" = "string2"

or

[ "$sting1" = "$string2" ]

Note: the single = instead of ==, and always quote sting variables. Further, there is nothing wrong with using the test or [ operators, in fact, they are preferred when portability is needed. They simply lack some of the extended functionality of the [[ operator, such as character class comparison and the ability to use =~.

Now when using the [[ operator, the correct form is:

[[ "$sting1" == "$string2" ]]

Note: as pointed out, quotes are not required when using the [[ operator, but if you get in the habit of always quoting strings, you will be safe in both cases.

Upvotes: 1

rje
rje

Reputation: 6418

You are using the "classic test" but it's a good idea to ALWAYS use the newer conditional expression: http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression

if [[ "$name" == "$username" ]]

As far as I know the test command (with a single bracket) doesn't even officially support the "==" operator..

Oh, and of course don't forget the spaces inside the brackets, bash needs them to break the line up into words.

Upvotes: 2

Related Questions