检查 Bash 中是否存在由另一个变量定义的变量

检查 Bash 中是否存在由另一个变量定义的变量

我正在看但我正在尝试使其适应我的情况,即我不对变量名称进行硬编码。事实上,我正在结合逻辑我之前的问题

像这样的东西:

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

编辑(来自@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

附加信息(来自bash手册):

当不执行子字符串扩展时,Bash 使用下面描述的形式(例如“:-”)测试未设置或为 null 的参数。省略冒号会导致仅测试未设置的参数。换句话说,如果包含冒号,则操作员会测试两者参数存在且其值不为空;如果省略冒号,则运算符仅测试是否存在。

答案1

特别是在 Bash 中,您可以使用[[ -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

也适用于例如[[ -v ${var/%__*} ]]

或者您可以使用带有 nameref 的“替代值”扩展(但您需要该临时变量):

$ 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

或者与间接扩展相同${!var},即${!var+set}等。

相关内容