ShellCheck show the following error for this line of code:
printf '%d' $(($(< "$1") + 1)) > "$1"
Is this really a problem? Could reading and writing the same file result in a race condition?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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.
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.