加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在函数Bash中:如何检查参数是否是一个set变量?

发布时间:2020-12-15 17:02:22 所属栏目:安全 来源:网络整理
导读:我想实现一个bash函数,test是第一个参数实际上是一个变量,在某处定义. 例如,在我的.bashrc中: customPrompt='yes';syntaxOn='no';[...]function my_func { [...] # I want to test if the string $1 is the name of a variable defined up above # so somet
我想实现一个bash函数,test是第一个参数实际上是一个变量,在某处定义.

例如,在我的.bashrc中:

customPrompt='yes';
syntaxOn='no';
[...]
function my_func {
    [...]
    # I want to test if the string $1 is the name of a variable defined up above
    # so something like: 
    if [[ $$1 == 'yes' ]];then 
         echo "$1 is set to yes";
    else
         echo "$1 is not set or != to yes";
    fi
    # but of course $$1 doesn't work
}

需要输出:

$my_func customPrompt
> customPrompt is set to yes
$my_func syntaxOn
> syntaxOn is set but != to yes
$my_func foobar
> foobar is not set

我尝试了很多测试,比如-v“$1”,-z“$1”,– n“$1”,但是所有这些都测试$1作为字符串而不是变量.
(如果我不明白,请纠正我)

在bash中,您可以使用间接变量子句.
t1=some
t2=yes
fufu() {
    case "${!1}" in
        yes) echo "$1: set to yes. Value: ${!1}";;
        '')  echo "$1: not set. Value: ${!1:-UNDEF}";;
        *)   echo "$1: set to something other than yes. Value: ${!1}";;
    esac
}

fufu t1
fufu t2
fufu t3

版画

t1: set to something other than yes. Value: some
t2: set to yes. Value: yes
t3: not set. Value: UNDEF

bash中的${!variablename}意味着间接变量扩展.在例如https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Whrere:

The basic form of parameter expansion is ${parameter}. The value of
parameter is substituted. The braces are required when parameter is a
positional parameter with more than one digit,or when parameter is
followed by a character that is not to be interpreted as part of its
name.

If the first character of parameter is an exclamation point (!),a
level of variable indirection is introduced. Bash uses the value of
the variable formed from the rest of parameter as the name of the
variable; this variable is then expanded and that value is used in the
rest of the substitution,rather than the value of parameter itself.
This is known as indirect expansion. The exceptions to this are the
expansions of ${!prefix } and ${!name[@]} described below. The
exclamation point must immediately follow the left brace in order to
introduce indirection.

另外,检查一下:https://stackoverflow.com/a/16131829/632407如何在函数中修改间接传递的变量的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读