Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test strings for lexicographic less than or equal in Bash?

Tags:

bash

In Bash, is there a simple way to test if one string is lexicographically less than or equal to another?

I know you can do:

if [[ "a" < "b" ]] 

for testing strict inequality, or

if [[ 1 -le 1 ]] 

for numbers. But -le doesn't seem to work with strings, and using <= gives a syntax error.

like image 484
tskuzzy Avatar asked Jan 22 '14 21:01

tskuzzy


People also ask

How do I test a string in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

How do I compare two string variables in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

Can you compare strings in bash?

The need to compare strings in a Bash script is relatively common and can be used to check for certain conditions before proceeding on to the next part of a script. A string can be any sequence of characters. To test if two strings are the same, both strings must contain the exact same characters and in the same order.

How do you check if two strings are equal in shell script?

Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.


1 Answers

Just negate the greater than test:

if [[ ! "a" > "b" ]] 
like image 146
Gordon Davisson Avatar answered Oct 01 '22 08:10

Gordon Davisson