# Thread: If Else Variable Notation (SHELL SCRIPT)

Enjoy an ad free experience by logging in. Not a member yet? Register.
1. ## If Else Variable Notation (SHELL SCRIPT)

What's the difference between

(A) if [ \$1 = 1 ]; then...

and

(B) if [ "\$1" = 1 ]; then...

and

(C) if [ "\$1" -eq 1 ]; then...

and which one is the correct notation?

2. For (A), [ \$1 = 1 ] is just wrong. First of all, if you are comparing strings, you should use ==, not =. Single = should be reserved for variable assignment. If you are comparing strings, you should also put quotes around the right-hand side value.

Same goes with (B), except that the double-quotes around "\$1" will preserve spaces in the argument. Also use the quotes on the right hand side, e.g.:
Code:
` if [ "\$1" == '1' ]`
For (C), it is assumed you are comparing numbers, by virtue of the -eq, therefore, you don't need the quotes aournd the \$1, e.g.:
Code:
` if [ \$1 -eq 1 ]`
I leave it to you to decide what is right, as it is based upon what you are trying to do (comparing strings vs numbers, etc.).

3. "=" is an operator that tests equality in strings. "-eq" tests it for integers. I think for equality, the two would actually work the same, but for some inequalities, they wouldn't. For example 10 -gt 2 but "10" < "2".

Putting quotes round a variable simply ensures that, if the value contains a space or some other special character, it won't cause problems.
@atreyu: I think it is "=" in bash, "==" in C.

4. \$spacer_open \$spacer_close
5. I guess they're both considered okay. According to the bash manpage:
Code:
```       string1 == string2
True  if  the  strings  are  equal.   = may be used in place of == for
strict POSIX compliance.```
i usually just read the first sentence. :P

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•