【发布时间】:2013-12-07 07:16:15
【问题描述】:
我一直在创建一个小型 bash 函数库,以将一些更神秘的 bash 语法结构封装到我可以快速使用和引用的例程中。但是对于其中一些,我的函数遇到了意外的返回码。下面的“is_undefined”函数就是这样一个例子。谁能解释我得到的结果? (也在下面提供。)
#!/bin/bash
is_undefined ()
{
# aka "unset" (not to be confused with "set to nothing")
# http://stackoverflow.com/questions/874389/bash-test-for-a-variable-unset-using-a-function
[ -z ${1+x} ]
}
if [ -z ${UNDEFINED+x} ]; then
echo "inline method reports that \$UNDEFINED is undefined"
fi
if is_undefined UNDEFINED; then
echo "is_undefined() reports that \$UNDEFINED is undefined"
else
echo "is_undefined() reports that \$UNDEFINED is defined"
fi
DEFINED=
if is_undefined DEFINED; then
echo "is_undefined() reports that \$DEFINED is undefined"
else
echo "is_undefined() reports that \$DEFINED is defined"
fi
令人惊讶的结果是:
$ ./test.sh
inline method reports that $UNDEFINED is undefined
is_undefined() reports that $UNDEFINED is defined
is_undefined() reports that $DEFINED is defined
【问题讨论】:
-
添加
set -vx以查看何时处理的方式/内容。祝你好运。 -
最新版本的
bash有一个-v运算符来测试是否设置了变量。[[ -v foo ]]仅在未设置foo时成功;如果foo设置为空字符串,则失败。 -
关于 -v:几个月前我设法将它加入到我的代码中,但忘记记录参考。我昨晚删除了它,因为我没有在我的 bash 书中找到它,并且谷歌搜索它没有产生任何结果。我想我一定是想象出来的……我想不是! :)
-
哦,我对
-v的描述完全倒退了:(-v foo在foo是设置时为真,否则为假。在4.2中引入。
标签: bash function return-code