Double quote array expansions to avoid re-splitting elements. Open
for KEY in ${KEYS[@]}; do
- Read upRead up
- Exclude checks
Double quote array expansions to avoid re-splitting elements.
Problematic code:
cp $@ ~/dir
Correct code:
cp "$@" ~/dir
Rationale:
Double quotes around $@
(and similarly, ${array[@]}
) prevents globbing and word splitting of individual elements, while still expanding to multiple separate arguments.
Let's say you have three arguments: baz
, foo bar
and *
"$@"
will expand into exactly that: baz
, foo bar
and *
$@
will expand into multiple other arguments: baz
, foo
, bar
, file.txt
and otherfile.jpg
Since the latter is rarely expected or desired, ShellCheck warns about it.
Exceptions
When you want globbing of individual elements.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Can't follow non-constant source. Use a directive to specify location. Open
[ -e "$CONFIG_DIR/barista/keys" ] && . "$CONFIG_DIR/barista/keys"
- Read upRead up
- Exclude checks
Can't follow non-constant source. Use a directive to specify location.
Problematic code:
. "$(find_install_dir)/lib.sh"
Correct code:
# shellcheck source=src/lib.sh
. "$(find_install_dir)/lib.sh"
Rationale:
ShellCheck is not able to include sourced files from paths that are determined at runtime. The file will not be read, potentially resulting in warnings about unassigned variables and similar.
Use a [[Directive]] to point shellcheck to a fixed location it can read instead.
Exceptions:
If you don't care that ShellCheck is unable to account for the file, specify # shellcheck source=/dev/null
.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.