help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Solved: Re: Distinguish between unset and empty variable


From: Dmitry Alexandrov
Subject: Re: [Help-bash] Solved: Re: Distinguish between unset and empty variables in loop.
Date: Thu, 15 Dec 2016 05:36:04 +0300
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.0.50 (gnu/linux)

> Just for the record, here is a solution of the problem:
>
>       xxx=hi;
>       yyy="";
>       unset zzz;
>       for i in xxx yyy zzz; do
>               (set -o posix; set | grep -q "^$i=") || eval "$i=default"; echo 
> $i=${!i};
>       done
>
> It prints
>
>       xxx=hi
>       yyy=
>       zzz=default
>
> as desired.
>
> This is clearly a hack, but it just works, so who cares.

OMG.

,----[ (info "(bash) Bash Conditional Expressions") ]
| `-v VARNAME'
|      True if the shell variable VARNAME is set (has been assigned a
|      value).
`----

,----[ ./warlich ]
| #!/bin/bash
| 
| xxx=hi
| yyy=""
| unset zzz
| 
| for v in xxx yyy zzz; do
|     [[ -v $v ]] || printf -v "$v" 'default'
|     printf '%s=%s\n' "$v" "${!v}"
| done
`----

,----
| $ ./warlich
| xxx=hi
| yyy=
| zzz=default
`----



reply via email to

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