mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2010 (markdown)
36
SC2010.md
36
SC2010.md
@@ -3,22 +3,42 @@
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
ls /directory | grep target_file_pattern
|
||||
ls /directory | grep mystring
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```sh
|
||||
rm $(ls | grep -v '\.c$')
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
ls /directory/target_file_pattern
|
||||
echo /directory/*mystring*
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```sh
|
||||
# BASH
|
||||
shopt -s extglob
|
||||
rm -- !(*.c)
|
||||
|
||||
# POSIX
|
||||
for f in ./*
|
||||
do
|
||||
case $f of
|
||||
*.c) true;;
|
||||
*) rm "$f";;
|
||||
esac
|
||||
done
|
||||
```
|
||||
|
||||
### Rationale:
|
||||
|
||||
Matching non-alphanumeric characters with grep may require escaping. Typically it is cleaner to use the built in pattern matching or another command like `find`
|
||||
[Parsing ls](https://mywiki.wooledge.org/ParsingLs) is generally a bad idea because the output is fragile and human readable. To better handle non-alphanumeric filenames, use a glob. If you need more advanced matching than a glob can provide, use a `for` loop.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
Matching the negative list.
|
||||
|
||||
```sh
|
||||
ls /directory | grep -v NOT_target_file_pattern
|
||||
```
|
||||
None
|
Reference in New Issue
Block a user