mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2081 (markdown)
30
SC2081.md
Normal file
30
SC2081.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
## `[ .. ]` can't match globs. Use `[[ .. ]]` or grep.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
if [ $var == *[^0-9]* ]
|
||||||
|
then
|
||||||
|
echo "$var is not numeric"
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
if [[ $var == *[^0-9]* ]]
|
||||||
|
then
|
||||||
|
echo "$var is not numeric"
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
`[ .. ]` aka `test` can not match against globs.
|
||||||
|
|
||||||
|
In bash/ksh, you can instead use `[[ .. ]]` which supports this behavior.
|
||||||
|
|
||||||
|
In sh, you can rewrite to use `grep`.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
None. If you are not trying to match a glob, quote the argument (e.g. `[ $var == '*' ]` to match literal asterisk.
|
Reference in New Issue
Block a user