[Rear-users] Better way to extend arrays in bash (+=)

Werner Flamme werner.flamme at ufz.de
Thu Apr 23 12:59:34 CEST 2009


Schlomo Schapiro [23.04.2009 12:15]:
> Hi,
> 
> while reading the bash manpage I found this little gem:
> 
> A variable may be assigned to by a statement of the form
> 
> name=[value]
> 
> If  value  is  not  given,  the variable is assigned the null string.
> All values undergo tilde expansion, parameter and variable expansion,
> command substitution, arithmetic  expansion,  and  quote  removal
> (see EXPANSION below).  If the variable has its integer attribute
> set, then value is evaluated as an arithmetic expression even if the
> $((...)) expansion is not used (see Arithmetic Expansion below).
> Word splitting is not performed, with the exception of "$@" as
> explained below under Special Parameters.  Pathname expansion is not
> performed.  Assignment statements may also appear as arguments  to
> the  alias,  declare,  typeset, export, readonly, and local builtin
> commands.

In "GNU bash, version 2.05b.0(1)-release-(x86_64-suse-linux)" (on my
SLES 9) the text ends here. Nothing of += is mentioned.

> 
> Which means that instead of writing tediously
> 
> VAR=( "${VAR[@]}" some "more stuff" )
> 
> we can now simply write
> 
> VAR+=( better "and nicer stuff" )

[...]

> 
> I found this in bash 3.2.25. Can you please check with your bash
> version and post wether it also works there? Of course only for
> Kernel 2.6 systems (as that is what ReaR supports).
> 

This does not work for me on the SLES 9 boxes:
STRING="foo"
STRING+=" bar"
bash: STRING+= bar: command not found
STRING+="bar"
bash: STRING+=bar: command not found
echo $STRING
foo

But it works as described on my openSUSE 11.1 (GNU bash, version
3.2.39(1)-release (x86_64-suse-linux-gnu))

> I would then suggest to migrate to the new form of extending arrays
> as it looks better and reduces code complexity. No need to go through
> all scripts and change it but I would use it with new code.
> 
> Regards, Schlomo
> 
> PS: And those who wonder are encouraged to do man bash :-)
> 
> PPS: For those who don't know. ReaR depends on bash version 3 and not
> on "sh"! That is why we allow ourselves to use the arrays and other
> fancy stuff and MUST use #!/bin/bash instead of #!/bin/sh !
Hm, yes, bash v3 - but all my SLES 9 boxes have the same bash as
mentioned above, and ReaR runs...

BTW, I will be using SLES 9 up to next year, when the SAP hardware in my
company will change. Maybe I even have to switch to Slowlaris... ISO
output? Hmmmmmmmm........

Regards,
Werner




More information about the rear-users mailing list