Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > gnu.bash.bug > #15722
| From | Léa Gris <lea.gris@noiraude.net> |
|---|---|
| Newsgroups | gnu.bash.bug |
| Subject | Re: Two states of empty arrays |
| Date | 2019-12-12 22:04 +0100 |
| Organization | French Data Network |
| Message-ID | <mailman.749.1576184670.1979.bug-bash@gnu.org> (permalink) |
| References | <c9224e23-ff7d-ba84-dc4f-aa68db902f72@noiraude.net> <79b6365d-4c09-7122-25c3-4564fd304948@case.edu> <mailman.740.1576178010.1979.bug-bash@gnu.org> <qsua0m$fkh$1@solo.fdn.fr> |
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
Back to gnu.bash.bug | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Re: Two states of empty arrays Chet Ramey <chet.ramey@case.edu> - 2019-12-12 14:13 -0500 Re: Two states of empty arrays Léa Gris <lea.gris@noiraude.net> - 2019-12-12 22:04 +0100 Re: Two states of empty arrays Martin Schulte <gnu@schrader-schulte.de> - 2019-12-12 22:34 +0100
csiph-web