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

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

问题描述

一个简单的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的答案,我被带到了猛砸的一部分页,我已经忽略了几百次:

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的页说:如果名称不是一个数组,如果名称设置否则返回null扩展到0。对于这种真值表的目的,它的行为同样的,即使它是一个数组。

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.

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

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