bug-bash
[Top][All Lists]
Advanced

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

Re: Document m=1 m=2; echo $m result


From: Greg Wooledge
Subject: Re: Document m=1 m=2; echo $m result
Date: Sun, 2 Jul 2023 21:04:38 -0400

On Sun, Jul 02, 2023 at 08:56:08PM -0400, Lawrence Velázquez wrote:
> On Sun, Jul 2, 2023, at 8:30 PM, Dan Jacobson wrote:
> > OK, but do please mention somewhere that "if the variable is set more
> > than once within the same statement, the final value is used."
> >
> > $ m=1 m=2;  echo $m
> > #(Yes, acts the same as:)
> > $ m=1; m=2; echo $m

It's more than this.

> This is stated under "Simple Command Expansion".
> 
>       When a simple command is executed, the shell performs the
>       following expansions, assignments, and redirections, from
>       left to right, in the following order.
> 
>         [...]
> 
>       4.  The text after the = in each variable assignment undergoes
>           tilde expansion, parameter expansion, command substitution,
>           arithmetic expansion, and quote removal before being
>           assigned to the variable.
> 
> https://www.gnu.org/software/bash/manual/html_node/Simple-Command-Expansion.html

Each variable assignment within the simple command is done, one at a
time, left to right.  It's not "the last one wins".

    unicorn:~$ m=1 m=$((m+3)); echo "$m"
    4

The first assignment is done before the value of "m" is used in the second
assignment.  They can build upon each other.

This feature is commonly used in the following constructs:

    extract=${input#*<} extract=${extract%>*}

    data=$(cat file; printf x) data=${data%x}



reply via email to

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