I am doing integer comparison in bash (trying to see if the user is running as root), and I found two different ways of doing it:
Double equals:
if [ $UID == 0 ] then fi
-eq
if [ $UID -eq 0 ] then fi
I understand that there’s no >= or <= in bash, only -ge and -le, so why is there a == if there’s a -eq?
Is there a difference in the way it compares both sides?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
== is a bash-specific alias for =, which performs a string (lexical) comparison instead of the -eq numeric comparison. (It’s backwards from Perl: the word-style operators are numeric, the symbolic ones lexical.)
Method 2
To elaborate on bollovan’s answer…
There is no >= or <= comparison operator for strings. But you could use them with the ((...)) arithmetic command to compare integers.
You can also use the other string comparison operators (==, !=, <, >, but not =) to compare integers if you use them inside ((...)).
Examples
- Both
[[ 01 -eq 1 ]]and(( 01 == 1 ))do integer comparisons. Both are true. - Both
[[ 01 == 1 ]]and[ 01 = 1 ]do string comparisons. Both are false. - Both
(( 01 -eq 1 ))and(( 01 = 1 ))will return an error.
Note: The double bracket syntax [[...]] and the double parentheses syntax ((...)) are not supported by all shells.
Method 3
If you want to do integer comparison you will better use (( )), where you can also use >= etc.
Example:
if (( $UID == 0 )); then echo "You are root" else echo "You are not root" fi
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0