为什么我的bash函数返回一个意外的返回码?

时间:2013-12-06 22:54:44

标签: bash function return-code

我一直在创建一个小型的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

2 个答案:

答案 0 :(得分:3)

is_undefined UDEFINED返回true,因为is_undefined内的测试不会测试UNDEFINED但是$1,而$1 定义。它的值是UNDEFINED

因此,只要提供参数,您的函数应始终返回true。唯一一次它将返回false,应该是在你没有参数的情况下调用它

is_undefined

要让is_undefined测试实际变量,您可以使用带有感叹号!的变量间接,请参阅Shell Parameter Expansion

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}" ]
}

答案 1 :(得分:3)

is_undefined内你正在测试$1,而不是${UNDEFINED},你需要抛出变量间接,比如

is_undefined () {
    [ -z "${!1+x}" ]
}

然而,这是基础而不是posix兼容。对于posix compliacy,您需要

is_undefined () {
    eval "[ -z \${$1+x} ]"
}