Skip to content
Joachim Ansorg edited this page Nov 12, 2021 · 2 revisions

Quote expansions in this for loop glob to prevent wordsplitting, e.g. "$dir"/*.txt .

Problematic code:

for file in $dir/*.txt
do
  echo "Found $file"
done

Correct code:

for file in "$dir"/*.txt
do
  echo "Found $file"
done

Rationale:

When iterating over globs containing expansions, you can still quote all expansions in the path to better handle whitespace and special characters.

Just make sure glob characters are outside quotes. "$dir/*.txt" will not glob expand, but "$dir"/*.txt or "$dir"/*."$ext" will.

Exceptions:

Exceptions similar to SC2086 apply. If the variable is expected to contain globs, such as if dir="tmp/**" in the example, you can ignore this message.

Related resources:

  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally