bug-bash
[Top][All Lists]
Advanced

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

Re: How to presence-detect an array variable or subscript thereof with `


From: Greg Wooledge
Subject: Re: How to presence-detect an array variable or subscript thereof with `test -v`?
Date: Tue, 27 Nov 2012 14:19:36 -0500
User-agent: Mutt/1.4.2.3i

On Tue, Nov 27, 2012 at 07:57:28PM +0100, Tim Friske wrote:
> I came accross the `-v` option of the `test` command and wondered how I
> would possibly test not only string- and integer- but also array variables
> as a whole and in parts.

Sounds more like a help-bash question than a bug-bash question.

For a single element, I'd drop the test -v entirely and just use the
standard methods:

  if [[ ${array[i]+set} ]]; then echo "array element i is set"; fi

(See http://mywiki.wooledge.org/BashFAQ/083).

For whole arrays, it's murkier, because arrays and strings can be
transformed into each other at will.  Referencing element 0 of an array
is the same thing as referencing a scalar by the same name:

  $ unset array; array=(zero one two); echo "$array"
  zero
  $ unset string; string="foo"; echo "${string[0]}"
  foo

However, bash actually does seem to track whether a variable was
initialized as a single-element array, or as a string:

  $ unset a; a=(x); declare -p a
  declare -a a='([0]="x")'
  $ unset b; b=x; declare -p b
  declare -- b="x"

So, if you care about that particular distinction, you could find some
bash-specific test (possibly "declare -p", or possibly something else)
to distinguish them.  Otherwise, they are exactly the same:

  $ echo "<$a> <$b> <${a[0]}> <${b[0]}> ${#a[*]} ${#b[*]}"
  <x> <x> <x> <x> 1 1



reply via email to

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