[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] ${var:?message} customization
From: |
Stephane Chazelas |
Subject: |
Re: [Help-bash] ${var:?message} customization |
Date: |
Fri, 15 May 2015 12:13:34 +0100 |
User-agent: |
Mutt/1.5.21 (2010-09-15) |
2015-05-14 17:38:27 -0500, Dan Douglas:
> On Thu, May 14, 2015 at 7:23 AM, Greg Wooledge <address@hidden> wrote:
> > (That's all using POSIX sh syntax. Recent versions of bash have a
> > "test -v" command, but I don't think it adds much utility.)
>
> test -v comes from ksh. I used to think it was necessary because
> testing whether an element of an array or compound variable is set
> isn't as simple as testing whether the zeroth element is set as in
> bash, because an array or compound var may contain an array or other
> type whose "setness" is independent of its container. However I don't
> know offhand of a case where it differs from ${var+word}. You have to
> admit it's generally easier to understand when there's a dedicated way
> to test.
ksh's test -v behaviour seems to differ from bash's test -v for
arrays or associative arrays that have been assigned to an empty
list. Both consider that a declared by never assigned variable
is unset though:
$ ksh -c 'typeset -a a; test -v a; echo "$?"; a=(); test -v a; echo "$?"'
1
0
$ bash -c 'typeset -a a; test -v a; echo "$?"; a=(); test -v a; echo "$?"'
1
1
In ksh:
ksh -c 'a=(); test -v "a[0]"; echo "$?"'
returns 0, which is not very consistent with address@hidden being
zero. But is probably a consequence of $a being the same as
${a[0]} instead of having separate data types for scalar and
arrays.
In zsh (where arrays and scalars are separate and arrays are
arrays), you have:
${+var} to test if a variable is set. It expands to 0 or 1
depending on wether it's set or not. That's reminiscent of
${#var} that expands to the number of elements (number of
characters for scalars, number of elements for arrays or
associations).
So:
(($+var)) && echo var is set
(($#var)) && echo var is non-empty
does what you generally expect for scalar/array/associations.
(($+var[key])) is only relevant for arrays/associations though
(not that it would make a lot of sense to use it for scalars).
In zsh, declaring a variable makes it show as "set"
--
Stephane
Re: [Help-bash] ${var:?message} customization, Matias A. Fonzo, 2015/05/14
Re: [Help-bash] ${var:?message} customization, Dan Douglas, 2015/05/14
- Re: [Help-bash] ${var:?message} customization,
Stephane Chazelas <=