简体   繁体   中英

Order of arithmetic expansion

Consider the following:

for i in 1 2 3; do echo $(( j += 1 ))& done

According to (my reading of) the sh language spec , section 2.3 paragraph 5, the arithmetic expansion of j += 1 should take place during token recognition, and should thus be processed before the shell ever reads the & . So it seems that executing the above line should increment j by 3 and each invocation of echo should get a different argument. (Which is the behavior if '&' is replaced by ';'). In bash 3.2.25, j is not modified. Is this a bug in bash, or am I misunderstanding something?

That entire token recognition section deals with parsing , not expansion or command evaluation of any kind. Have a look at the "introduction" for context - parsing comes before basically everything, while evaluation of the arithmetic expression is usually one of the very last evaluation steps. It isn't really relevant here.

You're probably actually wondering about whether expansions occur before the subshell forks for asynchronous lists. They don't.

 $ ksh93 -c 'typeset -i n; while ((++j%10)); do { n+=1; printf "$n "; } & done; while ((++j%10)); do : $((n++)) ${ printf "$n " >&2;} & done 2>&1; echo'
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 $
 $ bash -c 'f() { printf "#%d %s, %s\n" "$@"; }; f 1 $BASHPID $$; f 2 $BASHPID $$ & sleep 1'      
#1 12275, 12275
#2 12276, 12275
 $

As for the order of expansions, arithmetic expansion is performed at the same time as parameter expansion and command substitution, from left-to-right (also as shown above in the second loop).

I think you're not the only one to misread that section, I've filed a number of bugs related to it which have turned out to be either an error on my part or due to some unfortunate interaction with non-POSIX shell extensions. IMHO that section is too terse.

If you think there's a problem with the spec language or the implementations you'll likely find better answers on one of the mailing lists. ast-users , help-bash , austin group lists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM