The definition for an array being set is from bash manual:
An array variable is considered set if a subscript has been assigned a value. The null string is a valid value.
Does it mean that an array is set if and only if the number of its elements is greater than zero?
Is the following array set,
myarr=()
?The manual also says
A parameter is set if it has been assigned a value. The null string is a valid value.
Since an array is also a parameter, how does the definition of an array being set agree with the definition of a parameter being set?
For example,
myvar=""
is set, but ismyarr=()
set? Hasmyarr
been assigned a value, which is null?
There is a different definition for an array being set from https://unix.stackexchange.com/a/246703/674
For shells that support arrays, except for yash and zsh that would not report as set array variables unless the element of indice 0 has been set.
For bash (but not ksh93 nor zsh), for variables of type associative array, that would not report them as set unless their element of key "0" has been set.
Is this definition incorrect, because an array name without subscription actually refers to the element indexed by index/key
0
instead of referring to the entire array, according to Bash manualReferencing an array variable without a subscript is equivalent to referencing with a subscript of 0.
So is this definition actually for the element indexed by index/key
0
being set, not for the array being set?For example,
${myarr+1}
and[[ -v myarr ]]
are the applications to an arraymyarr
the usual ways of testing if a variable/parameter is set. Which doesmyarr
in them mean:myarr[0]
, or the entire arraymyarr
?What is POSIX definition for a shell array being set?
Asked
Active
Viewed 385 times
0
1 Answers
0
- Does it mean that an array is set if and only if the number of its elements is greater than zero?
Yes.
- Is the following array set, myarr=()?
No.
- how does the definition of an array being set agree with the definition of a parameter being set?
Both are meant to be equal, I see no problem here:
A parameter is set if it has been assigned a value. The null string is a valid value.
An array variable is considered set if ... has been assigned a value. The null string is a valid value.
- There is a different definition ...
What the answer at https://unix.stackexchange.com/a/246703/674 is describing is the details of how the test [ -n "${var+set}" ]
work, not defining what is set or not, not for normal variables, not for arrays.
Please note the that
in that would not report ...
.
- What is POSIX definition for a shell array being set?
There are no "shell arrays" in POSIX.
set -u; x=([1]=b); echo $x
orset -u; declare -A x; x=([a]=b); echo $x
, then try the same with 0 instead of 1 anda
respectively. – choroba May 03 '16 at 20:05x
inecho $x
meanx[0]
or the array? Does your example test which one is set,x[0]
or the array? – Tim May 03 '16 at 21:56