基本上,我有这个if语句完成了所有需要的东西
if [ -z "${x}" ]; then
echo "You must set x variable, please see readme.md on how to get & set this variable."
exit 1
fi
但我发现了一个更酷的解决方案:
echo "${x:?You must set x variable, please see readme.md on how to get & set this variable.}
它也可以工作,但它有一个主要问题,如果变量存在它打印到cmd,是否有可能以某种方式只显示错误,如果变量存在不显示它的内容?
是否有可能在1个函数中传递2个变量?像这样:
echo "${x,y:?You must set x,y variable, please see readme.md on how to get & set this variable.}
您可以使用no-op (:
):
: ${x:?x is empty or not set} ${y:?y is empty or not set}
或
: ${x?x is not set} ${y?y is not set}
注意empty和not set的区别。
你也可以测试一个变量是否被设置:
[[ -v x ]] || { echo x is not set >&2; exit 1; }
我有时确实使用no-op的东西,但通常我为错误做一个die函数:
die()
{
echo "$@" >&2
exit 1
}
[[ -v x ]] || die x is not set
编辑:我说你需要一个测试来检查变量是否设置是错误的。我记不住语法了,文档里也没有。
与其他展开逻辑一样,您可以省略冒号(:
)以将检查从if为空更改为if未设置。因此,如果x未设置,${x?}
将导致错误(如果设置并为空则没有错误),如果x未设置或设置但为空,${x:?}
将导致错误。
我相应地修改了答案。