Updated SC3012 (markdown)

Vidar Holen
2021-03-31 20:36:05 -07:00
parent d6bacbfe35
commit dbcf6e6139

@@ -1,27 +1,44 @@
## In POSIX sh, lexicographical \> is undefined. ## In POSIX sh, lexicographical \< is undefined.
### Problematic code: ### Problematic code:
```sh ```sh
#!/bin/sh #!/bin/sh
x=1.31 x="aardvark"
y=1.29 y="zebra"
! [ $x \> $y ] if [ $x \< $y ]
then
echo "$x comes before $y in the dictionary"
fi
``` ```
### Correct code: ### 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: ### 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: ### Exceptions:
Please expand on this section. If you know your `sh` will be e.g. `dash`, consider explicitly using `#!/bin/dash`.
### Related resources: ### Related resources: