EN
Bash - check if string is greater than (ASCII alphabetical order)
0
points
In this article, we would like to show you how to check if check if string is greater than another string in Bash.
Practical example
In this example, we use escaped > operator to check if string is greater than another string (in ASCII alphabetical order) inside the if statement.
script.sh file:
#!/bin/bash
string="bbb"
if [ "$string" \> "aaa" ]; then
echo "The $string is greater than aaa"
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
./script.sh
Output:
The bbb is greater than aaa
Altermative notation
1. test based solution
#!/bin/bash
string="bbb"
if test "$string" \> "aaa"; then
echo "The $string is greater than aaa"
fi
Note:
[ ]notation is shorthand oftestcommand.
2. [[ ]] based solution
#!/bin/bash
string="bbb"
if [[ "$string" > "aaa" ]]; then
echo "The $string is greater than aaa"
fi
Note:
[[ ]]notation is like extendedtestcommand, adding additional features (e.g. regular expressions).