mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2203 (markdown)
39
SC2203.md
Normal file
39
SC2203.md
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
## Globs are ignored in [[ ]] except right of =/!=. Use a loop.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
[[ current.log -nt backup/*.log ]] && echo "This is the latest file"
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
newerThanAll=true
|
||||||
|
for log in backup/*.log
|
||||||
|
do
|
||||||
|
[[ current.log -nt "$log" ]] || newerThanAll=false
|
||||||
|
done
|
||||||
|
[[ "$newerThanAll" = "true" ]] && echo "This is the latest file"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
Globs in `[[ ]]` will not filename expand, and will be treated literally (or as patterns on the right-hand side of `=`, `==` and `!=`).
|
||||||
|
|
||||||
|
The problematic code is equivalent to `[[ current.log -nt 'backup/*.png' ]`, and will look for a file with a literal asterisk in the name.
|
||||||
|
|
||||||
|
Instead, you can iterate over the filenames you want with a loop, and apply your condition to each filename.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you know your glob will only ever match one file, you can check this explicitly and use the first file:
|
||||||
|
|
||||||
|
```
|
||||||
|
set -- backup/*.log
|
||||||
|
[[ $# -eq 1 ]] || { echo "There are too many matches."; exit 1; }
|
||||||
|
[[ file.log -nt "$1" ]] && echo "This is the latest file"
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatively, [[ignore]] this warning.
|
Reference in New Issue
Block a user