help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Why does this do what it does: $((name)) ?


From: Greg Wooledge
Subject: Re: Why does this do what it does: $((name)) ?
Date: Thu, 3 Jul 2025 10:31:35 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Thu, Jul 03, 2025 at 09:33:33 -0400, Greg Wooledge wrote:
> On Thu, Jul 03, 2025 at 07:26:03 -0600, Stan Marsh wrote:
> > And, finally, again, where can I read about this wonderful "feature"?  I 
> > couldn't find
> > it in "man bash".
> 
> It's implied by the text in the ARITHMETIC EVALUATION section:
> 
>        Shell variables are allowed as operands; parameter  expansion  is  per‐
>        formed before the expression is evaluated.  Within an expression, shell
>        variables may also be referenced by name without  using  the  parameter
>        expansion  syntax.  A shell variable that is null or unset evaluates to
>        0 when referenced by name without using the parameter expansion syntax.
>        The  value  of a variable is evaluated as an arithmetic expression when
>        it is referenced, or when a variable which has been given  the  integer
>        attribute using declare -i is assigned a value.  A null value evaluates
>        to 0.  A shell variable need not have its integer attribute  turned  on
>        to be used in an expression.
> 
> Note "The  value  of a variable is evaluated as an arithmetic expression"
> here.  That's a recursive definition.

Also, just for the record:

hobbit:~$ x='3+4'
hobbit:~$ echo $((5*x)) $((5*$x))
35 19

If you use the $x form, the variable is expanded as a string before
the expression is evaluated, which leads to potentially surprising
results.  If you use the no-$ form, the expression is evaluated
recursively, and the results are less surprising.

The only(?) dangerous part happens when you have array subscripting
in one of the variables.  The array subscripting syntax allows a
command substitution to occur inside it, which is where the code
injection potential arises.

Another version of this same explanation can be found at
<https://mywiki.wooledge.org/BashProgramming/05#Arithmetic_Expansion>.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]