Bash – Shellcheck complains that I should not to read and write the same file in the same pipeline

bashio-redirectionshellshellcheck

ShellCheck show the following error for this line of code:

printf '%d' $(($(< "$1") + 1)) > "$1"

Make sure not to read and write the same file in the same pipeline

Is this really a problem? Could reading and writing the same file result in a race condition?

Best Answer

Yes, reading and writing from the same file in parallel could result in a race condition. An input and an output redirection for the same file on the same command would truncate the file before starting to read it.

But no, this isn't what's happening here. It's a false positive in Shellcheck. Here the redirection is inside an arithmetic expression. All substitutions (arithmetic, variable, command, as well as splitting and globbing) are performed before redirections are executed. So at the time > "$1" opens the file, the reading bit is finished.

Related Question