Skip to content
Vidar Holen edited this page Aug 31, 2021 · 2 revisions

Redirection applies to the find command itself. Rewrite to work per action (or move to end).

Problematic code:

find . -name '*.ppm' -exec pnmtopng {} > {}.png \;

Correct code:

find . -name '*.ppm' -exec sh -c 'pnmtopng "$1" > "$1.png"' _ {} \;

Rationale:

ShellCheck detected a find command with a redirection in the middle.

This redirection may have been intended to apply only to a specific action like -exec or -print, but it does in fact apply to the entire find command:

# This command
find . -name '*.ppm' -exec pnmtopng {} > {}.png \;

# Is the same as this
{
   find . -name '*.ppm' -exec pnmtopng {} \;
} > {}.png 

To perform a redirection per action, rewrite it with e.g. -exec sh -c '...' _ {} \;

Exceptions:

If the redirection is something like > /dev/null where you don't mind it applying to the whole find and not individual results, you can move the redirection to the end of command to make it clear to ShellCheck (and humans) that it's not meant per command:

find . -exec foo {} > /dev/null \;     # Ambiguous syntax. Is it per -exec or not?
find . -exec foo {} \;  > /dev/null    # Identical command with clear intent.

There is no difference in behavior between the two.

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