一个简单的Bash变量测试:
${varName:? "${varName} is not defined"}
我想重用这个,通过把它放在一个函数。
怎么样?
以下失败
# # 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 }
也就是说如果测试失败,我需要退出。
感谢lhunath的回答,我被引导到Bash人页面的一部分,我忽略了几百次:
原文链接:https://www.f2er.com/bash/389369.htmlWhen 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.
这促使我创建以下真值表:
| 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的人页面说“如果name不是一个数组,如果name设置为0,否则扩展为0。为了这个真值表的目的,它的行为相同,即使它是一个数组。