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.
Disregard it, just read the Bash manual more. :-)
– Hossy Mar 28 '23 at 18:54