mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Updated SC3012 (markdown)
33
SC3012.md
33
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:
|
||||
|
||||
|
Reference in New Issue
Block a user