如何在 bash中的替代值扩展( ${var+alt}
)中使用一个变量的值作为另一个变量的名称?
我会认为
#!/bin/bash
cat='dog'
varname='cat'
if [ -z ${`echo "${varname}"`+x} ]; then
echo 'is null'
fi
应该大致相当于
#!/bin/bash
if [ -z ${dog+x} ]; then
echo 'is null'
fi
但是当我尝试这样做时,我得到
${`echo "${cat}"`+x}: bad substitution
我想部分问题是执行命令替换的子shell不再知道$varname
了?我需要导出该变量吗?
我这样做的原因是我从这个答案中学到了如何检查变量是否为空,并且我试图将该检查封装在一个名为 的函数中is_null
,如下所示:
function is_null {
if [ $# != 1 ]; then
echo "Error: is_null takes one argument"
exit
fi
# note: ${1+x} will be null if $1 is null, but "x" if $1 is not null
if [ -z ${`echo "${1}"`+x} ]; then
return 0
else
return 1
fi
}
if is_null 'some_flag'; then
echo 'Missing some_flag'
echo $usage
exit
fi