From 06fa07f854fdf314ffd7a572c813adeeb9b4c67d Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 21 Jan 2018 12:34:36 -0800 Subject: [PATCH] Created SC2227 (markdown) --- SC2227.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 SC2227.md diff --git a/SC2227.md b/SC2227.md new file mode 100644 index 0000000..c311a36 --- /dev/null +++ b/SC2227.md @@ -0,0 +1,41 @@ +## Redirection applies to the find command itself. Rewrite to work per action (or move to end). + +### Problematic code: + +```sh +find . -name '*.ppm' -exec pnmtopng {} > {}.png \; +``` + +### Correct code: + +```sh +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 '...' _ {} \;` + +If the redirection is something like `> /dev/null` where you don't mind it applying to the whole `find` and not individual results, move the redirection to the end of command: + + find . -exec foo {} > /dev/null \; # Ambiguous syntax. Is it per -exec or not? + find . -exec foo {} \; > /dev/null # Identical command with clear intent. + +### Exceptions: + +None + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file