Skip to content
Lawrence Velázquez edited this page Mar 8, 2024 · 4 revisions

In POSIX sh, lexicographical \< is undefined.

Problematic code:

#!/bin/sh
x="aardvark"
y="zebra"
if [ $x \< $y ]
then
  echo "$x comes before $y in the dictionary"
fi

Correct code:

First, 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"
fi

Rationale:

The 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.

Exceptions:

If you know your sh will be e.g. dash, consider explicitly using #!/bin/dash.

Related resources:

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally