mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Syntax highlighting and markdown
40
SC2046.md
40
SC2046.md
@@ -1,19 +1,23 @@
|
|||||||
# Quote this to prevent word splitting
|
# Quote this to prevent word splitting.
|
||||||
|
|
||||||
### Problematic code:
|
### Problematic code:
|
||||||
|
|
||||||
ls -l $(getfilename)
|
```sh
|
||||||
|
ls -l $(getfilename)
|
||||||
|
```
|
||||||
|
|
||||||
### Correct code:
|
### Correct code:
|
||||||
|
|
||||||
# getfilename outputs 1 file
|
```sh
|
||||||
ls -l "$(getfilename)"
|
# getfilename outputs 1 file
|
||||||
|
ls -l "$(getfilename)"
|
||||||
|
|
||||||
# getfilename outputs multiple files, linefeed separated
|
# getfilename outputs multiple files, linefeed separated
|
||||||
getfilename | while IFS='' read -r line
|
getfilename | while IFS='' read -r line
|
||||||
do
|
do
|
||||||
ls -l "$line"
|
ls -l "$line"
|
||||||
done
|
done
|
||||||
|
```
|
||||||
|
|
||||||
### Rationale:
|
### Rationale:
|
||||||
|
|
||||||
@@ -27,15 +31,19 @@ If the command substitution outputs multiple pieces of data, use a loop instead.
|
|||||||
|
|
||||||
In rare cases you actually want word splitting, such as in
|
In rare cases you actually want word splitting, such as in
|
||||||
|
|
||||||
# shellcheck disable=SC2046
|
```sh
|
||||||
gcc $(pkg-config --libs openssl) client.c
|
# shellcheck disable=SC2046
|
||||||
|
gcc $(pkg-config --libs openssl) client.c
|
||||||
|
```
|
||||||
|
|
||||||
This is because `pkg-config` outputs `-lssl -lcrypto`, which you want to break up by spaces into `-lssl` and `-lcrypto`.
|
This is because `pkg-config` outputs `-lssl -lcrypto`, which you want to break up by spaces into `-lssl` and `-lcrypto`.
|
||||||
|
|
||||||
A bash alternative in these cases is to use `read -a` for words or `mapfile` for lines. ksh can also use `read -a`, or a `while read` loop for lines. In this case, since `pkg-config` outputs words, you could use:
|
A bash alternative in these cases is to use `read -a` for words or `mapfile` for lines. ksh can also use `read -a`, or a `while read` loop for lines. In this case, since `pkg-config` outputs words, you could use:
|
||||||
|
|
||||||
# Read words into an array in bash and ksh
|
```sh
|
||||||
read -ra args < <(pkg-config --libs openssl)
|
# Read words into an array in bash and ksh
|
||||||
|
read -ra args < <(pkg-config --libs openssl)
|
||||||
# expand args
|
|
||||||
gcc "${args[@]}" client.c
|
# expand args
|
||||||
|
gcc "${args[@]}" client.c
|
||||||
|
```
|
Reference in New Issue
Block a user