5 ms·
Until you realize that some of the expressions in [[ are evaluated as arithmetic expression which has some surprises around array subscript and command substitu
by Calzifer 2y ago
Until you realize that some of the expressions in [[ are evaluated as arithmetic expression which has some surprises around array subscript and command substitution.
In short, because the following works despite quoting and will execute the echos
a=(); x='a[$(echo >&2 what; echo 0)]'; [[ 'x' -eq 0 ]]
I'm back to use the single [ for the arithmetic binary operators.
- patrakov 2y agoThanks! Added this example to my training slides.
- jolmg 2y agoThe relevant parts from the bash manpage: > arg1 OP arg2 > OP is one of -eq, -ne, -lt, -le, -gt, or -ge. [...] When used with the [[ command, Arg1 and Arg2 are evaluated as arithmetic expressions (see ARITHMETIC EVALUATION above). > ARITHMETIC EVALUATION > Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. > The value of a variable is evaluated as an arithmetic expression when it is referenced > Arrays > The subscript is treated as an arithmetic expression that must evaluate to a number. > [[ expression ]] > The shell performs [...] arithmetic expansion, command substitution [...] on those words. Given that reading, that both subscripts and values of variables in arithmetic expression are treated as arithmetic expressions, and that command substitution is peformed after arithmetic expansion in `[[`, I kinda expected the following to work: $ x='$(echo >&2 what; echo 0)'; [[ 0 -eq x ]] bash: [[: $(echo >&2 what; echo 0): syntax error: operand expected (error token is "$(echo >&2 what; echo 0)") I don't see in the docs what it is about array subscripts that makes them special with regards to command substitutions in arithmetic expressions.
- deleted 2y ago[deleted]
- jwilk 2y agoI don't fully understand what's going on here, but note that arithmetic expansion is for stuff like $((6 * 7)). There's no arithmetic expansion involved in your or Calzifer's examples.
- deleted 2y ago[deleted]
- jolmg 2y agoYou mean this part of my comment: >> The shell performs [...] arithmetic expansion, command substitution [...] on those words. > [...] and that command substitution is peformed after arithmetic expansion in `[[` [...] You're right. That doesn't apply. I was equating "arithmetic expansion" with "evaluation of arithmetic expressions", but I see now the former is specifically about `$(())`.