mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2046 (markdown)
19
SC2046.md
19
SC2046.md
@@ -27,24 +27,15 @@ 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
|
||||||
gcc $(pkg-config --libs openssl) client.c
|
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`. An alternative is to put the variables to an array and expand it:
|
This is because `pkg-config` outputs `-lssl -lcrypto`, which you want to break up by spaces into `-lssl` and `-lcrypto`.
|
||||||
|
|
||||||
# For bash
|
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:
|
||||||
mapfile -t args < <(pkg-config --libs openssl)
|
|
||||||
|
|
||||||
# For ksh
|
# Read words into an array in bash and ksh
|
||||||
pkg-config --libs openssl | while IFS="" read -r line; do array+=("$line"); done
|
read -ra args < <(pkg-config --libs openssl)
|
||||||
|
|
||||||
# expand args
|
# expand args
|
||||||
gcc "${args[@]}" client.c
|
gcc "${args[@]}" client.c
|
||||||
|
|
||||||
The power of using an array becomes evident when you want to combine, for example, the command result with user-provided arguments:
|
|
||||||
|
|
||||||
compile () {
|
|
||||||
args=( "$(pkg-config --libs openssl)" "${@}" )
|
|
||||||
gcc "${args[@]}" client.c
|
|
||||||
}
|
|
||||||
compile -DDEBUG
|
|
||||||
+ gcc -lssl -lcrypto -DDEBUG client.c
|
|
Reference in New Issue
Block a user