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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Yes, this is a problem, you can never read and write from/to the same pipe. Think of it this way: writing a file would set it to start as empty, and then reading from it would not yield anything.
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0