From dbcf6e6139af93a529598f1f531d9d8b003f85c0 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Wed, 31 Mar 2021 20:36:05 -0700 Subject: [PATCH] Updated SC3012 (markdown) --- SC3012.md | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/SC3012.md b/SC3012.md index 38748d7..fe1e8b8 100644 --- a/SC3012.md +++ b/SC3012.md @@ -1,27 +1,44 @@ -## In POSIX sh, lexicographical \> is undefined. +## In POSIX sh, lexicographical \< is undefined. ### Problematic code: ```sh #!/bin/sh -x=1.31 -y=1.29 -! [ $x \> $y ] +x="aardvark" +y="zebra" +if [ $x \< $y ] +then + echo "$x comes before $y in the dictionary" +fi ``` ### Correct code: -The easiest fix is to switch to a shell that *does* support lexicographical \>. +First, make sure you wanted a lexicographical comparison (aka dictionary order), and not a numerical comparison. -Please add common code examples. +The easiest fix is to switch to a shell that *does* support lexicographical comparison with `>`/`\>`, such as `bash`, `dash`, or `ksh`. Otherwise, you can use `awk` to compare lexicographically by making sure the strings contain at least some non-numerical data: + +``` +#!/bin/sh +x="aardvark" +y="zebra" +if awk -v first="'$x'" -v second="'$y'" 'BEGIN { exit (first < second) ? 0 : 1 }' +then + echo "$x comes before $y in the dictionary" +fi +``` + +The extra quotes in the awk `-v` flag are there to add non-numerical data to the string, otherwise `10 < 2` is treated as a numerical comparison (being false) instead of a lexicographical string comparison (being true). Any other non-numerical data can be used instead, such as `-v x="FOO$x"`. ### Rationale: -Please expand on this section. +The `test` binary operators `>`, `\>`, `<`, and `\<` are not part of POSIX and not guaranteed to be supported in scripts targeting `sh`. + +The `awk` functionality is POSIX and can safely be relied on. ### Exceptions: -Please expand on this section. +If you know your `sh` will be e.g. `dash`, consider explicitly using `#!/bin/dash`. ### Related resources: