将变量名传递给函数以测试是否存在和非空

我是新手

B)我的bash脚本提供了一个(用户可编辑的)配置脚本,在这里我想使用一个函数来测试变量的存在和非空。

在我的脚本中,我有这个:

# check if constant exists
${_CONFIG_VERSION+"false"} && exitLogged "" "Constant _CONFIG_VERSION not set in ${_CONFIG_FILE}"
${_HOSTNAME+"false"} && exitLogged "" "Constant _HOSTNAME not set in ${_CONFIG_FILE}"
${_SYSTEM_NAME+"false"} && exitLogged "" "Constant _SYSTEM_NAME not set in ${_CONFIG_FILE}"
${_SP_LINK_CFG_FILENAME+"false"} && exitLogged "" "Constant _SP_LINK_CFG_FILENAME not set in ${_CONFIG_FILE}"
...

# check if constant has a value
if [[ -z "${_CONFIG_VERSION}" ]]; then exitLogged "" "Constant _CONFIG_VERSION not set in ${_CONFIG_FILE}"; fi
if [[ -z "${_HOSTNAME}" ]]; then exitLogged "" "Constant _HOSTNAME not set in ${_CONFIG_FILE}"; fi
if [[ -z "${_SYSTEM_NAME}" ]]; then exitLogged "" "Constant _SYSTEM_NAME not set in ${_CONFIG_FILE}"; fi
if [[ -z "${_SP_LINK_CFG_FILENAME}" ]]; then exitLogged "" "Constant _SP_LINK_CFG_FILENAME not set in ${_CONFIG_FILE}"; fi
...

...但是想要这样做:

checkIfExistAndNonEmpty _CONFIG_VERSION
checkIfExistAndNonEmpty _HOSTNAME
checkIfExistAndNonEmpty _SYSTEM_NAME
checkIfExistAndNonEmpty _SP_LINK_CFG_FILENAME

...具有伪代码的功能,如下所示:

function checkIfExistAndNonEmpty() {
    arg1=${1}
    "$"{$arg1+"false"} && exitLogged "" "Constant $arg1 not set in ${_CONFIG_FILE}"        
    if [[ -z "${arg1}" ]]; then ...; fi
}

exitLogged()记录传入和退出的两个参数($ LINENO $ msg)。

这样的功能“ checkIfExistAndNonEmpty()”是否可能?

目的是传递变量名。将其重建为一个变量,我可以测试其是否存在和是否为空。

通常,如果重复相同的事情,那么就推入一个函数中……但是我可能会要求一些不可能的事情。

[编辑] 我看了一下...但是真的不明白...

function checkIfExistAndNonEmpty() {
    suffix=$1
    echo "suffix:$suffix"
    declare prefix_$suffix=$1
    # ...and then...
    varname=prefix_$suffix
    echo "varname:${!varname}"
    echo "---"
}
评论