Hi Everyone.
I looked around and have yet to find a solution so I was wondering. In bash how would I compare whether an argument is equal to some string.
Currently I have :
if [ $1 -eq 'someString' ]
This doesn't seem to work so I was wondering what might?
Thanks!
5 replies to this topic
#1
Posted 02 November 2011 - 01:29 PM
|
|
|
#2
Posted 07 November 2011 - 08:25 PM
if [[ $1 == 'someString' ]]; then
#blah
fi
You can also do != and, if you want to get fancy, use =~ with a regular expression on the right-hand-side.
sudo rm -rf /
#3
Posted 08 November 2011 - 05:57 AM
String comparison operators in bash are the same as the numeric comparison operators in other languages.
bash is an odd language because technically all variables are implemented as strings. I don't know why strings use the numeric comparison symbols though.
if [[ "$str1" == "$str2" ]] then # do stuff elif [[ "$str1" < "$st2" ]] then # do stuff else # do stuff fi
bash is an odd language because technically all variables are implemented as strings. I don't know why strings use the numeric comparison symbols though.
Programming is a journey, not a destination.
#4
Posted 08 November 2011 - 10:07 AM
Numbers use flags like -eq -gt -ge, etc. I think part of the reason why they're implemented as strings is because [ is actually its own program, not a true operation. The return value is what the if statement looks at.
If used on the command line, passing < | > or & would cause the shell to treat them as pipes or whatever, which would screw up the entire operation. With the [[ ]] construct, which isn't a program, you're allowed to use < and >. Because of the alphabetical sorting nature, it will also work for positive integers, but once you stick a negative sign in front of it, it breaks.
This is why we use those flags. Otherwise you get something like Perl, where you'd have to force a string comparison on strings that represent valid integers.
If used on the command line, passing < | > or & would cause the shell to treat them as pipes or whatever, which would screw up the entire operation. With the [[ ]] construct, which isn't a program, you're allowed to use < and >. Because of the alphabetical sorting nature, it will also work for positive integers, but once you stick a negative sign in front of it, it breaks.
[[ "3" > "4" ]] --> false [[ "3" < "4" ]] --> true [B] [[ "3" > "-4" ]] --> false[/B] [[ "-3" < "4" ]] --> true
This is why we use those flags. Otherwise you get something like Perl, where you'd have to force a string comparison on strings that represent valid integers.
Edited by dargueta, 08 November 2011 - 10:24 AM.
Formatting
sudo rm -rf /
#5
Posted 09 November 2011 - 07:26 AM
Hey, I just wanted to say thanks you. I never knew that Bash stored everything as strings but this makes more sense.
#6
Posted 09 November 2011 - 11:25 AM
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









