From ab166b1ef955e36423d494f900c5ebf2fac04f19 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Mon, 17 Feb 2020 18:36:57 -0800 Subject: [PATCH] Created SC2257 (markdown) --- SC2257.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 SC2257.md diff --git a/SC2257.md b/SC2257.md new file mode 100644 index 0000000..b76b59d --- /dev/null +++ b/SC2257.md @@ -0,0 +1,38 @@ +## Arithmetic modifications in command redirections may be discarded. Do them separately. + +### Problematic code: + +```sh +curl "$URL" > "image$((i++)).jpg" +``` + +### Correct code: + +```sh +i=$((i+1)) +curl "$URL" > "image$i.jpg" +``` +### Rationale: + +You are using an arithmetic expression that modifies a variable, e.g. `$((x+=1))` or `$((x++))`, in the name of a file to redirect from/to, in a here document, or in a here string. + +The scope of these modifications depends on whether the command itself will fork: + +```sh +echo foo > $((var++)).txt # Updates in BusyBox and Bash +cat foo > $((var++)).txt # Updates in Busybox, not in Bash +gcc foo > $((var++)).txt # Does not update in either + +gcc() { /opt/usr/bin/gcc "$@"; } +gcc foo > $((var++)).txt # Now suddenly updates in both +``` + +Rather than rely on knowing which commands do and don't fork, or are and aren't overridden, simply do the updates in a separate command as in the correct code. + +### Exceptions: + +If you know your variable is scoped the way you want it, you can ignore this warning. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file