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: Martin Schulte
Subject: Re: Two states of empty arrays
Date: Thu, 12 Dec 2019 22:34:52 +0100

Hello Léa!

Léa Gris <lea.gris@noiraude.net> wrote:
> 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

Just for the curious: What is your attention here?

I think that most useful questions (Is there an element in the array? Is
there a value for a given key?) can be answered in a simpler way:

#!/bin/bash

set -o nounset

# From what I learned today it seems to be good practice to always
# assign and empty array to when declaring an associative array:
declare -A assoc=()

echo ${#assoc[@]} # Are there elements in it?

assoc[key1]=val1
assoc[key2]=

for key in key1 key2 key3; do
  if [[ -n ${assoc[$key]+isset} ]]; then
    echo "Element for $key is set"
  else
    echo "No Element for $key"
  fi
done

Best regards,

Martin



reply via email to

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