使用函数测试未设置的Bash变量 [英] Test for a Bash variable being unset, using a function

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

问题描述

一个简单的Bash变量测试:

A simple Bash variable test goes:

${varName:?    "${varName} is not defined"}

我想通过将其放在函数中来重复使用它. 好吗?

I'd like to re-use this, by putting it in a function. How please?

关注失败

#
# Test a variable exists
tvar(){
 val=${1:?    "${1}    must be defined, preferably in $basedir"}
 if [ -z ${val}  ]
     then 
     echo Zero length value 
 else
     echo ${1} exists, value ${1}
 fi
}

即如果测试失败,我需要退出.

I.e. I need to exit if the test fails.

推荐答案

感谢 lhunath的回答,我被引到Bash man页面的一部分,而我却忽略了数百次:

Thanks to lhunath's answer, I was led to a part of the Bash man page that I've overlooked hundreds of times:


    When  not performing substring  expansion, bash tests for a parameter that
    is unset  or null; omitting the colon results in a test only for a parame‐
    ter that is unset.

这提示我创建以下真值表:

This prompted me to create the following truth table:



                | unset |   set    | set and  | meaning
                |       | but null | not null |
    ============+=======+==========+==========+=============================
     ${var-_}   |   T   |     F    |    T     | not null or not set
    ------------+-------+----------+----------+-----------------------------
     ${var:-_}  |   T   |     T    |    T     | always true, use for subst.
    ------------+-------+----------+----------+-----------------------------
     $var       |   F   |     F    |    T     | var is set and not null
    ------------+-------+----------+----------+-----------------------------
     ${!var[@]} |   F   |     T    |    T     | var is set

此表在最后一行中介绍了规范. Bash man页显示如果name不是数组,则在设置name时扩展为0,否则为null".出于此真值表的目的,即使它是数组,其行为也相同.

This table introduces the specification in the last row. The Bash man page says "If name is not an array, expands to 0 if name is set and null otherwise." For purposes of this truth table, it behaves the same even if it's an array.

这篇关于使用函数测试未设置的Bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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