bug-bash
[Top][All Lists]
Advanced

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

Re: Two states of empty arrays


From: Léa Gris
Subject: Re: Two states of empty arrays
Date: Thu, 12 Dec 2019 22:04:22 +0100
User-agent: Telnet/1.0 [tlh] (PDP11/DEC)

Le 12/12/2019 à 20:13, Chet Ramey écrivait :

>> # Empty array declared without parenthesis
>> unset myArr
>> declare -a myArr
>> typeset -p myArr
>> echo "${#myArr[@]}"
> 
> This is an unset variable with the array attribute; you have not assigned a
> value.
>> # Empty array declared without parenthesis
>> unset myArr
>> declare -a myArr=()
> 
> This is an empty array variable; you have assigned a value.

Thank you and Clint, it makes sense now.

I was trying to play the the -v test to detect when an array or
associative array has been declared, not necessarily assigned entries
key, values, to not error when Bash runs with -o nounset

Like here:
#!/usr/bin/bash
set -o nounset
myArr+=(["key"]="value")

ERR: line 3: key: unbound variable

I can test the type of myArr this way:
if [[ "$(typeset -p myArr 2>&1)" =~ ^declare\ -A ]]; then
  myArr+=(["key"]="value")
fi

But it looks sub-optimal to test the type and declaration of a variable.
The -v test flag cannot be used because it requires the associative
array to contain at least a [key]=value entry as mentioned in the man
bash.1:

>        -v varname
>               True if the shell variable varname is set (has been assigned a 
> value).

_has been assigned a value_

-- 
Lea Gris




reply via email to

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