【发布时间】:2015-04-03 12:32:09
【问题描述】:
如何在 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 了?我需要导出那个变量吗?
我这样做的原因是我从this answer 那里学到了如何检查变量是否为空,并且我正在尝试将这种检查封装在一个名为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
【问题讨论】:
-
@Ashwani 谢谢,这正是我所需要的。我将 if 语句更改为
if [ -z ${!1+x} ]; then ...
标签: bash variable-expansion variable-substitution