2

I'm looking at this but I'm trying to adapt it to my case where I don't hardcode the variable name. In fact, I'm combining logic from a previous question of mine.

Something like this:

shopt -s extglob
export var=abc_def__123__456
echo ${var/%__*}
# does this variable (abc_def) exist?
echo This is not valid syntax: [ -z ${${var/%__*}+x} ] && echo ${var/%__*} does not exist
echo Effectively checking this: [ -z ${abc_def+x} ] && echo abc_def does not exist
shopt -u extglob

EDIT (answer from @ikkachu):

shopt -s extglob
export var=abc_def__123__456
# does this variable (abc_def) exist?
if [[ ! -v ${var/%__*} ]]; then echo ${var/%__*} does not exist; fi
# does this variable (abc_def) exist? (with temp variable)
export temp=${var/%__*}
echo ${temp}
if [ ! -z ${temp+x} ]; then echo \'temp\' exists; fi # checks temp variable only
if [ -z ${!temp+x} ]; then echo ${temp} does not exist; fi
if [ -z ${abc_def+x} ]; then echo abc_def does not exist; fi
shopt -u extglob

Additional information (from Bash manual):

When not performing substring expansion, using the form described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

1 Answer 1

4

In Bash in particular, you can use [[ -v var ]]:

$ foo=1; unset bar;
$ varname=foo
$ if [[ -v $varname ]]; then echo set; else echo not set; fi
set
$ varname=bar
$ if [[ -v $varname ]]; then echo set; else echo not set; fi
not set

Works with e.g. [[ -v ${var/%__*} ]] too.

Or you can use "alternate value" expansion with a nameref (but you need that temporary variable):

$ declare -n ref=foo
$ if [[ ${ref+set} = set ]]; then echo set; else echo not set; fi
set
$ declare -n ref=bar
$ if [[ ${ref+set} = set ]]; then echo set; else echo not set; fi
not set

Or the same with the ${!var} indirect expansion, i.e. ${!var+set} etc.

2
  • Thank you! I can't seem to find the reference for the alternate value expansion. Do you happen to have a link or could point me to something to search for? Disregard it, just read the Bash manual more. :-) Commented Mar 28, 2023 at 18:54
  • 2
    @Hossy, this is a case where the POSIX text is perhaps easier to read than Bash's manual, at least they have a nice table of all the cases: pubs.opengroup.org/onlinepubs/9699919799/utilities/… Commented Mar 28, 2023 at 19:06

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.