Before showing two variants of a number comparison statement, I want to show an alternative method counting the occurrence of a string in another one.
The following "grep -c" counts the occurrences of ":" in the echoed string:
echo "gu:gus:bla:bla" | grep -c ":"
Output
3
Another way to write the statement from above is:
grep -c ":" <<< "gu:gus:bla:bla"
Output
3
Here two examples of similar number comparison statements using the output of the statement from above:
OS> if (( $(grep -c ":" <<< "gugus:blabla") == 1 )); then echo "TRUE"; else echo "FALSE"; fi
TRUE
OS> if (( $(grep -c ":" <<< "gugus blabla") == 1 )); then echo "TRUE"; else echo "FALSE"; fi
FALSE
OS> if [[ $(grep -c ":" <<< "gugus:blabla") -eq 1 ]]; then echo "TRUE"; else echo "FALSE"; fi
TRUE
OS> if [[ $(grep -c ":" <<< "gugus blabla") -eq 1 ]]; then echo "TRUE"; else echo "FALSE"; fi
FALSE
I consider the first variant to be more elegant.
But if you are mixing character and numerical comparisons, you will need to use the 2nd variant with "[[ ... ]]"
For example:
X="Hello"; if [[ "${X}" == "Hello" && $(grep -c ":" <<< "gugus:blabla") -eq 1 ]]; then echo "TRUE"; else echo "FALSE"; fi
TRUE
X="Bella"; if [[ "${X}" == "Hello" && $(grep -c ":" <<< "gugus:blabla") -eq 1 ]]; then echo "TRUE"; else echo "FALSE"; fi
FALSE
The following syntax gives wrong results
OS> X="Xello"; if (( "${X}" == "Hello" && $(grep -c ":" <<< "gugus:blabla") == 1 )); then echo "TRUE"; else echo "FALSE"; fi
TRUE
OS> X="Bella"; if (( "${X}" == "Hello" && $(grep -c ":" <<< "gugus:blabla") == 1 )); then echo "TRUE"; else echo "FALSE"; fi
TRUE <== Wrong
Matematical
Syntax |
"In Words"
|
==
|
-eq
|
<
|
-lt
|
>
|
-gt
|
=<
|
-le
|
>=
|
-ge
|
!=
|
-ne
|
No comments :
Post a Comment