Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to be explicit about intentional word splitting?

I'm running shellcheck on my scripts and often get this warning (which in this case is correct, because cd foo bar baz makes no sense):

cd ${SOME_DIR} || exit 1
   ^-- SC2046: Quote this to prevent word splitting.

This warning is mostly a good one. One exception when the variable contains multiple arguments:

gcc ${OPTIONS} ...
    ^-- SC2046: Quote this to prevent word splitting.

Is there a convention for being more explicit about intentional word splitting, possibly avoiding this shellcheck warning?

like image 336
Andreas Avatar asked Dec 31 '22 00:12

Andreas


1 Answers

Simply add double quotes when no split is the intent:

cd "${SOME_DIR}" || exit 1

Perform explicit splitting into an array:

read -ra gcc_options <<<"${OPTIONS}"
gcc "${gcc_options[@]}"

Or disable shellcheck for the next statement, indicating you reviewed the operation as conform to the intent:

# shellcheck disable=SC2046 # Intended splitting of OPTIONS
gcc ${OPTIONS}

Sometimes Reading The Fine Manual is a better option than asking here:

Shellcheck gives links to its Wiki for code inspection warnings. The SC2046 Quote this to prevent word splitting wiki entry already mentions the use of read -a in Bash and how to disable this code inspection for specific cases with non-Bash shell grammars.

like image 86
Léa Gris Avatar answered Jan 22 '23 11:01

Léa Gris