Bash函数检查是否设置了给定变量 [英] Bash function to check if a given variable is set

查看:56
本文介绍了Bash函数检查是否设置了给定变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案中所述,检查bash中是否设置了变量的正确"方法如下所示::

As explained in this answer, the "right" way to check if a variable is set in bash looks like this:

if [ -z ${var+x} ]; then
    echo "var is unset"
else
    echo "var is set to '$var'"
fi

我感兴趣的是如何将其提取到可用于不同变量的函数中.

What I'm interested in is how to extract this into a function that can be reused for different variables.

到目前为止,我能做的最好的事情是:

The best I've been able to do so far is:

is_set() {
  local test_start='[ ! -z ${'
  local test_end='+x} ]'
  local tester=$test_start$1$test_end

  eval $tester
}

这似乎可行,但是有没有更好的方法而不是调用 eval ?

It seems to work, but is there a better way that doesn't resort to calling eval?

推荐答案

在Bash中,您可以使用 [[--v var]] .不需要功能或复杂的方案.

In Bash you can use [[ -v var ]]. There's no need for a function or convoluted schemes.

从联机帮助页:

   -v varname
          True if the shell variable varname is set (has been assigned a value).

前2个命令序列显示 ok :

[[ -v PATH ]] && echo ok

var="" ; [[ -v var ]] && echo ok

unset var ; [[ -v var ]] && echo ok

这篇关于Bash函数检查是否设置了给定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆