Comparing string and number - which one is correct?
Hello all
I'm trying to understand which is best practice. I want to compare string and also number. In this case which one i should use: Code:
CVAR="Done" Code:
CVAR="Done" Also, while checking for variable content for numbers, should i use -eq, -lt, -gt ..etc or =, <, > etc... Thanks |
Hi,
it really depends on which shell you are using. Evo2. |
Quote:
|
Hi,
ok, then the second one is wrong. The reason they are both giving the same answer is because the expressions after the || are not even being evaluated. Try setting CVAR to "notDone" and running your scripts. The (( foo )) is for evaluation not testing like [[ foo ]]. EVo2. |
That makes sense. Thanks for correcting the mistake. :)
|
I am not sure I exactly follow evo2's logic. The first part about the || make sense as an 'or' only requires one side to be true for the whole statement to test as true.
However, I am not sure I follow: Quote:
other '[[]]' can be used for either. As of the more recent versions of bash, it is clearer to the reader to perform arithmetic testing with the round and reserve the square brackets for strings and file testing as reflected when using the test command. In answer to the last part of your original question, when using the round brackets it is also clearer to use the typical mathematical symbols, ie. <, >, <=, etc You do also have the choice when testing in the round brackets to exclude the leading dollar sign as all strings used inside the brackets are looked at as variable names, so you could have written: Code:
(( NVAR == 123 )) |
Quote:
Code:
$ ((5 -eq 5)); echo $? |
Hi,
Quote:
Cheers, Evo2. PS. I find the "Advanced Bash-Scripting Guide" to be a good resource on these sort of topics. |
grail and rknichols thanks for your insights.
|
rknichols is of course correct, I was looking at [[]] when I was writing and mixed up which can use both ... oops
|
All times are GMT -5. The time now is 03:07 PM. |