-
Notifications
You must be signed in to change notification settings - Fork 1.9k
SC3012
Eisuke Kawashima edited this page Jul 29, 2025
·
5 revisions
#!/bin/sh
x="aardvark"
y="zebra"
if [ $x \< $y ]
then
echo "$x comes before $y in the dictionary"
fiFirst, make sure you wanted a lexicographical comparison (aka dictionary order), and not a numerical comparison.
Then to compare as string, you can use expr and make sure that the strings are not interpreted numerically by adding some non-numerical data to them. Here, an apostrophe is prepended:
#!/bin/sh
x="aardvark"
y="zebra"
if expr "'$x" \< "'$y" > /dev/null
then
echo "$x comes before $y in the dictionary"
fiThe test binary operators >, \>, <, and \< are not part of POSIX and not guaranteed to be supported in scripts targeting sh.
The expr functionality is specified by POSIX.
If you know your sh will be e.g. dash, consider explicitly using #!/bin/dash.