I don't have a concrete citation for why this behavior exists, but going off the notes in SC2257* there are some interesting points to note in the manual.
When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment
§3.7.3 Command Execution Environment
This reflects what SC2257 notes, though it's unclear about which environment the redirection's value is evaluated in. However §3.1.1 Shell Operation seems to say that redirection happens before this execution (sub)environment is invoked:
Basically, the shell does the following:
...
- Performs the various shell expansions....
- Performs any necessary redirections and removes the redirection operators and their operands from the argument list.
- Executes the command.
We can see that this isn't limited to arithmetic expansions but also other state-changing expansions like :=
:
$ bash -c 'date >"${word:=wow}.txt"; echo "word=${word}"'
word=
$ bash -c 'echo >"${word:=wow}.txt"; echo "word=${word}"'
word=wow
Interestingly, this does not appear to be a (well-defined) subshell environment, because BASH_SUBSHELL
remains set to 0
:
$ date >"${word:=$BASH_SUBSHELL}.txt"; ls
0.txt
We can also check some other shells, and see that zsh
has the same behavior, though dash
does not:
$ zsh -c 'date >"${word:=wow}.txt"; echo "word=${word}"'
word=
$ zsh -c 'echo >"${word:=wow}.txt"; echo "word=${word}"'
word=wow
$ dash -c 'date >"${word:=wow}.txt"; echo "word=${word}"'
word=wow
$ dash -c 'echo >"${word:=wow}.txt"; echo "word=${word}"'
word=wow
I skimmed the zsh
guide but didn't find an exact mention of this behavior there either.
Needless to say, this does not appear to be well-documented behavior, so it's fortunate that ShellCheck can help catch it. It does however appear to be long-standing behavior, it's reproducible in Bash 3, 4, and 5.
* Unfortunately the commit that added SC2257 doesn't link to an Issue or any other further context.
strace -f bash -c 'cnt=1; date > $((++cnt)).txt' |& egrep 'txt|clone'
. But then I guess you knew that. Whether it is documented I couldn't say.