Results 1 to 4 of 4
What's the difference between
(A) if [ $1 = 1 ]; then...
and
(B) if [ "$1" = 1 ]; then...
and
(C) if [ "$1" -eq 1 ]; then...
...
- 10-14-2011 #1Just Joined!
- Join Date
- Sep 2011
- Posts
- 6
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?
- 10-14-2011 #2Linux Guru
- Join Date
- May 2011
- Posts
- 1,838
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.:
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" == '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.).Code:if [ $1 -eq 1 ]
- 10-17-2011 #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."I'm just a little old lady; don't try to dazzle me with jargon!"
- 10-17-2011 #4Linux Guru
- Join Date
- May 2011
- Posts
- 1,838
I guess they're both considered okay. According to the bash manpage:
i usually just read the first sentence. :PCode:string1 == string2 True if the strings are equal. = may be used in place of == for strict POSIX compliance.


Reply With Quote