help-bash
[Top][All Lists]
Advanced

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

Re: Invisible contents of a variable array?


From: Greg Wooledge
Subject: Re: Invisible contents of a variable array?
Date: Sat, 21 Jan 2023 15:12:37 -0500

On Sat, Jan 21, 2023 at 02:30:32PM -0500, Roger wrote:
> The real magic here are the "()" parenthesis, acts similar to unset, clears
> the variables?  I do not see much within the bash manual concerning "()",
> except for functions suffix, etc.

An array assignment looks like:

varname=( stuff here )

The parentheses indicate that this is an array assignment, rather than
a string assignment.

If you perform the command above, you'll end up with an array containing
two elements:

unicorn:~$ varname=( stuff here )
unicorn:~$ declare -p varname
declare -a varname=([0]="stuff" [1]="here")

You can put a variety of things inside the parentheses to initialize the
array.  They can be plain strings, like above.  They can be expressions
containing substitutions, like "$stringvar" or "$HOME/bin".  They can be
glob patterns, which will be expanded by filename substitution.

unicorn:~$ varname=(*.txt)
unicorn:~$ declare -p varname
declare -a varname=([0]="37a.txt" [1]="68x68.txt" [2]="Application.txt" [...]

If there's NOTHING between the parentheses, then the array is initialized
with zero elements.

unicorn:~$ varname=()
unicorn:~$ declare -p varname
declare -a varname=()

That's it.  There's no magic here.  () is an empty array, just like "" is
an empty string.

What's actually magic (the bad kind of magic) is the fact that bash treats
"varname" and "varname[0]" with equivalence in most contexts.

unicorn:~$ declare -p varname
declare -a varname=()
unicorn:~$ varname=""
unicorn:~$ declare -p varname
declare -a varname=([0]="")

What's going on here?  varname was already an array, and I wrote varname=""
which means bash had to pretend I had written varname[0]="".

This equivalence is TERRIBLE, and I despise it.  But it's been this way for
many years, and I don't expect it to change.

unicorn:~$ varname=(an array with several elements)
unicorn:~$ echo "$varname"
an

varname is equivalent to varname[0] here, so you only get the 0th
element.  Is this useful?  HELL NO.  It doesn't even give you the first
element of the array, which *might* be useful.  You get the element with
index 0.

unicorn:~$ unset 'varname[0]'
unicorn:~$ declare -p varname
declare -a varname=([1]="array" [2]="with" [3]="several" [4]="elements")
unicorn:~$ echo "$varname"

unicorn:~$ 

See?  Useless.

It's just as dumb the other way around, too.

unicorn:~$ declare -p HOME
declare -x HOME="/home/greg"
unicorn:~$ echo "$HOME"
/home/greg
unicorn:~$ echo "${HOME[0]}"
/home/greg

Even when dealing with a regular string variable, varname and varname[0]
are equivalent.  It's daft!



reply via email to

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