Showing 1,039 of 1,039 total issues
Blank line contains whitespace Open
- Read upRead up
- Exclude checks
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
popd references arguments, but none are ever passed. Open
popd () {
- Read upRead up
- Exclude checks
foo references arguments, but none are ever passed.
Problematic code:
sayhello() {
echo "Hello $1"
}
sayhello
./myscript World
just prints "Hello " instead of "Hello World".
Correct code:
sayhello() {
echo "Hello $1"
}
sayhello "$@"
./myscript World
now prints "Hello World".
Rationale:
In a function, $1
and up refers to the function's parameters, not the script's parameters.
If you want to process your script's parameters in a function, you have to explicitly pass them. You can do this with myfunction "$@"
.
Note that "$@"
refers to the current context's positional parameters, so if you call a function from a function, you have to pass in "$@"
to both of them:
first() { second "$@"; }
second() { echo "The first script parameter is: $1"; }
first "$@"
Exceptions
If the parameters are optional and you currently just don't want to use them, you can ignore this message.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Consider using { cmd1; cmd2; } >> file instead of individual redirects. Open
echo '<html lang="en">' >> index.html
- Read upRead up
- Exclude checks
Consider using { cmd1; cmd2; } >> file instead of individual redirects.
Problematic code:
echo foo >> file
date >> file
cat stuff >> file
Correct code:
{
echo foo
date
cat stuff
} >> file
Rationale:
Rather than adding >> something
after every single line, you can simply group the relevant commands and redirect the group.
Exceptions
This is mainly a stylistic issue, and can freely be ignored.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Use popd "$@" if function's $1 should mean script's $1. Open
popd
- Read upRead up
- Exclude checks
Use foo "$@" if function's $1 should mean script's $1.
See companion warning [[SC2120]].
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
echo "<li><a href=\"$product/product-statistics/statistics.html\">Product Statistics</a></li>" >> $STATS_DIR/index.html
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
utils/gen_html_guides_index.py . $PAGES_DIR/guides/index.html
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Use find instead of ls to better handle non-alphanumeric filenames. Open
test -n "$public_key" || public_key=$(ls "$HOME"/.ssh/*.pub | head -n 1)
- Read upRead up
- Exclude checks
Use find instead of ls to better handle non-alphanumeric filenames.
Problematic code:
ls -l | grep " $USER " | grep '\.txt$'
Correct code:
find . -maxdepth 1 -name '*.txt' -user "$USER"
Rationale:
ls
is only intended for human consumption: it has a loose, non-standard format and may "clean up" filenames to make output easier to read.
Here's an example:
$ ls -l
total 0
-rw-r----- 1 me me 0 Feb 5 20:11 foo?bar
-rw-r----- 1 me me 0 Feb 5 2011 foo?bar
-rw-r----- 1 me me 0 Feb 5 20:11 foo?bar
It shows three seemingly identical filenames, and did you spot the time format change? How it formats and what it redacts can differ between locale settings, ls
version, and whether output is a tty.
ls
can usually be substituted for find
if it's the filenames you're after.
If trying to parse out any other fields, first see whether stat
(GNU, OS X, FreeBSD) or find -printf
(GNU) can give you the data you want directly.
Exceptions:
If the information is intended for the user and not for processing (ls -l ~/dir | nl; echo "Ok to delete these files?"
) you can ignore this error with a [[directive]].
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
To read lines rather than words, pipe/redirect to a 'while read' loop. Open
for rule in $(cat $UNSELECT_LIST); do
- Read upRead up
- Exclude checks
To read lines rather than words, pipe/redirect to a 'while read' loop.
Problematic code:
for line in $(cat file | grep -v '^ *#')
do
echo "Line: $line"
done
Correct code:
grep -v '^ *#' < file | while IFS= read -r line
do
echo "Line: $line"
done
or without a subshell (bash, zsh, ksh):
while IFS= read -r line
do
echo "Line: $line"
done < <(grep -v '^ *#' < file)
or without a subshell, with a pipe (more portable, but write a file on the filesystem):
mkfifo mypipe
grep -v '^ *#' < file > mypipe &
while IFS= read -r line
do
echo "Line: $line"
done < mypipe
rm mypipe
Rationale:
For loops by default (subject to $IFS
) read word by word. Additionally, glob expansion will occur.
Given this text file:
foo *
bar
The for loop will print:
Line: foo
Line: aardwark.jpg
Line: bullfrog.jpg
...
The while loop will print:
Line: foo *
Line: bar
Exceptions
If you want to read word by word, you should still use a while read loop (e.g. with read -a
to read words into an array).
Rare reasons for ignoring this message is if you don't care because your file only contains numbers and you're not interested in good practices, or if you've set $IFS
appropriately and also disabled globbing.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
sed -i "/<.*select.*idref=\"$rule/s/selected=\"true\"/selected=\"false\"/g" $DS || exit 1
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Check exit code directly with e.g. 'if mycmd;', not indirectly with $?. Open
if [ $? -ne 0 ]; then
- Read upRead up
- Exclude checks
Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.
Problematic code:
make mytarget
if [ $? -ne 0 ]
then
echo "Build failed"
fi
Correct code:
if ! make mytarget
then
echo "Build failed"
fi
Rationale:
Running a command and then checking its exit status $?
against 0 is redundant.
Instead of just checking the exit code of a command, it checks the exit code of a command (e.g. [
) that checks the exit code of a command.
Apart from the redundancy, there are other reasons to avoid this pattern:
- Since the command and its status test are decoupled, inserting an innocent command like
echo "make finished"
aftermake
will cause theif
statement to silently start comparingecho
's status instead. - Scripts that run or are called with
set -e
akaerrexit
will exit immediately if the command fails, even though they're followed by a clause that handles failure. - The value of
$?
is overwritten by[
/[[
, so you can't get the original value in the relevant then/else block (e.g.if mycmd; then echo "Success"; else echo "Failed with $?"; fi
).
To check that a command returns success, use if mycommand; then ...
.
To check that a command returns failure, use if ! mycommand; then ...
.
To additionally capture output with command substitution: if output=$(mycommand); then ...
This also applies to while
/until
loops.
Exceptions:
The default Solaris 10 bourne shell does not support '!' outside of the test command (if ! mycommand; then ...
returns !: not found
)
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Couldn't parse this brace group. Open
{{% endif %}}
- Read upRead up
- Exclude checks
Couldn't parse this ...
This parsing error points to the structure ShellCheck was trying to parse when a parser error occurred. See [[Parser error]] for more information.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
You need a space after the '{'. Open
{{% endif %}}
- Read upRead up
- Exclude checks
You need a space after the '{'.
Problematic code:
foo() {echo "hello world;}
Correct code:
foo() { echo "hello world;}
Rationale:
{
is only recognized as the start of a command group when it's a separate token.
If it's not a separate token, like in the problematic example, it will be considered a literal character, as if writing "{echo"
with quotes, and therefore usually cause a syntax error.
Exceptions:
None.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
You need a space after the '{'. Open
{{% endif %}}
- Read upRead up
- Exclude checks
You need a space after the '{'.
Problematic code:
foo() {echo "hello world;}
Correct code:
foo() { echo "hello world;}
Rationale:
{
is only recognized as the start of a command group when it's a separate token.
If it's not a separate token, like in the problematic example, it will be considered a literal character, as if writing "{echo"
with quotes, and therefore usually cause a syntax error.
Exceptions:
None.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
echo "</head>" >> $STATS_DIR/index.html
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
if [ -f build/$product/product-statistics/statistics.html ]; then
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Use popd "$@" if function's $1 should mean script's $1. Open
popd
- Read upRead up
- Exclude checks
Use foo "$@" if function's $1 should mean script's $1.
See companion warning [[SC2120]].
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Quote this to prevent word splitting. Open
content_cmakelists="$(realpath $(dirname ${BASH_SOURCE[0]}))/../CMakeLists.txt"
- Read upRead up
- Exclude checks
Quote this to prevent word splitting
Problematic code:
ls -l $(getfilename)
Correct code:
# getfilename outputs 1 file
ls -l "$(getfilename)"
# getfilename outputs multiple files, linefeed separated
getfilename | while IFS='' read -r line
do
ls -l "$line"
done
Rationale:
When command expansions are unquoted, word splitting and globbing will occur. This often manifests itself by breaking when filenames contain spaces.
Trying to fix it by adding quotes or escapes to the data will not work. Instead, quote the command substitution itself.
If the command substitution outputs multiple pieces of data, use a loop instead.
Exceptions
In rare cases you actually want word splitting, such as in
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:
args=( $(pkg-config --libs openssl) )
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
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
Double quote to prevent globbing and word splitting. Open
if ! [[ "$count" =~ ^[0-9]+$ ]] || [ $count -eq 0 ]; then
- Read upRead up
- Exclude checks
Double quote to prevent globbing and word splitting.
Problematic code:
echo $1
for i in $*; do :; done # this done and the next one also applies to expanding arrays.
for i in $@; do :; done
Correct code:
echo "$1"
for i in "$@"; do :; done # or, 'for i; do'
Rationale
The first code looks like "print the first argument". It's actually "Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result."
The second one looks like "iterate through all arguments". It's actually "join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list". The third one skips the joining part.
Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.
Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:
$HOME/$dir/dist/bin/$file # Unquoted (bad)
"$HOME"/"$dir"/dist/bin/"$file" # Minimal quoting (good)
"$HOME/$dir/dist/bin/$file" # Canonical quoting (good)
When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: "$HOME/$dir/src/*.c"
will not expand, but "$HOME/$dir/src"/*.c
will.
Note that $( )
starts a new context, and variables in it have to be quoted independently:
echo "This $variable is quoted $(but this $variable is not)"
echo "This $variable is quoted $(and now this "$variable" is too)"
Exceptions
Sometimes you want to split on spaces, like when building a command line:
options="-j 5 -B"
make $options file
Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):
options=(-j 5 -B) # ksh: set -A options -- -j 5 -B
make "${options[@]}" file
or a function (POSIX):
make_with_flags() { make -j 5 -B "$@"; }
make_with_flags file
To split on spaces but not perform glob expansion, Posix has a set -f
to disable globbing. You can disable word splitting by setting IFS=''
.
Similarly, you might want an optional argument:
debug=""
[[ $1 == "--trace-commands" ]] && debug="-x"
bash $debug script
Quoting this doesn't work, since in the default case, "$debug"
would expand to one empty argument while $debug
would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value:
debug=""
[[ $1 == "--trace-commands" ]] && debug="yes"
bash ${debug:+"-x"} script
This is better than an unquoted value because the alternative value can be properly quoted, e.g. wget ${output:+ -o "$output"}
.
As always, this warning can be [[ignore]]d on a case-by-case basis.
this is especially relevant when BASH many not be available for the array work around. For example, use in eval or in command options where script has total control of the variables...
FLAGS="-av -e 'ssh -x' --delete --delete-excluded"
...
# shellcheck disable=SC2086
eval rsync $FLAGS ~/dir remote_host:dir
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
This } is literal. Check expression (missing ;/\n?) or quote it. Open
{{% else %}}
- Read upRead up
- Exclude checks
This {
/}
is literal. Check expression (missing ;/\n?
) or quote it.
Problematic code:
rmf() { rm -f "$@" }
or
eval echo \${foo}
Correct code:
rmf() { rm -f "$@"; }
and
eval "echo \${foo}"
Rationale:
Curly brackets are normally used as syntax in parameter expansion, command grouping and brace expansion.
However, if they don't appear alone at the start of an expression or as part of a parameter or brace expansion, the shell silently treats them as literals. This frequently indicates a bug, so ShellCheck warns about it.
In the example function, the }
is literal because it's not at the start of an expression. We fix it by adding a ;
before it.
In the example eval, the code works fine. However, we can quiet the warning and follow good practice by adding quotes around the literal data.
ShellCheck does not warn about {}
, since this is frequently used with find
and rarely indicates a bug.
Exceptions
This error is harmless when the curly brackets are supposed to be literal, in e.g. awk {'print $1'}
. However, it's cleaner and less error prone to simply include them inside the quotes: awk '{print $1}'
.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.
The mentioned parser error was in this brace group. Open
{{% endif %}}
- Read upRead up
- Exclude checks
The mentioned parser error was in ...
This info warning points to the start of what ShellCheck was parsing when it failed. See [[Parser error]] for example and information.
Notice
Original content from the ShellCheck https://github.com/koalaman/shellcheck/wiki.