help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Distinguish between unset and empty variables in loop.


From: Greg Wooledge
Subject: Re: [Help-bash] Distinguish between unset and empty variables in loop.
Date: Wed, 23 Nov 2016 14:44:08 -0500
User-agent: Mutt/1.4.2.3i

On Wed, Nov 23, 2016 at 08:35:33PM +0100, Christof Warlich wrote:
> >The usual procedures to distinguish between unset and empty
> >variables   (i.e. [ -z ${var+x} ] or [[ -v var ]]) do not work
> >here, as the loop variable is always set.

Uh... yeah?

> Please revisit my example, taking the for-loop into account:
> 
>       xxx=hi:
>       yyy="";
>       for i in xxx yyy zzz; do
>               [ -z ${!i} ] && eval "$i=default"; echo $i=${!i};
>       done

Oh.  You're doing some bizarre indirection thing.  You want an associative
array instead.

> I can't see how to apply the ${var+x} (or ${x+hello}} pattern to this 
> situation.

declare -A map
map[xxx]=hi
map[yyy]=""
unset 'map[zzz]'

for i in xxx yyy zzz; do
  if test "${map[$i]+defined}"; then
    echo "element $i is defined in the map"
  fi
done

If you can't use an associative array because you're stuck with bash 3,
then my advice is to upgrade to bash 4, or switch to something that HAS
associative arrays, like awk, perl, python, tcl, ....



reply via email to

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