如何检查是否在 Bash 中设置了变量? [英] How to check if a variable is set in Bash?

查看:32
本文介绍了如何检查是否在 Bash 中设置了变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道 Bash 中是否设置了变量?

How do I know if a variable is set in Bash?

例如,我如何检查用户是否给函数提供了第一个参数?

For example, how do I check if the user gave the first parameter to a function?

function a {
    # if $1 is set ?
}

推荐答案

(通常)正确的方法

if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi

其中 ${var+x}参数扩展 如果 var 未设置,则计算结果为零,否则替换字符串 x.

where ${var+x} is a parameter expansion which evaluates to nothing if var is unset, and substitutes the string x otherwise.

引号可以省略(所以我们可以说 ${var+x} 而不是 "${var+x}"),因为这种语法 &用法保证这只会扩展到不需要引号的东西(因为它要么扩展到 x (它不包含分词,所以不需要引号),或者什么都没有(导致 [ -z ],它可以方便地计算出与 [ -z "" ] 相同的值 (true))).

Quotes can be omitted (so we can say ${var+x} instead of "${var+x}") because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to x (which contains no word breaks so it needs no quotes), or to nothing (which results in [ -z ], which conveniently evaluates to the same value (true) that [ -z "" ] does as well)).

然而,虽然可以安全地省略引号,但对所有人来说并不是很明显(甚至对 来说都不是很明显)这个引用解释的第一作者也是一个主要的 Bash 编码器),有时最好用引号来编写解决方案 [ -z "${var+x}" ],以 O(1) 速度损失的非常小的可能成本.第一作者还在使用此解决方案的代码旁边添加了此作为注释,给出了此答案的 URL,现在还包括解释为什么可以安全地省略引号.

However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to the first author of this quotes explanation who is also a major Bash coder), it would sometimes be better to write the solution with quotes as [ -z "${var+x}" ], at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.

if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi

这通常是错误的,因为它不区分未设置的变量和设置为空字符串的变量.也就是说,如果var='',那么上面的解决方案会输出var is blank".

This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var='', then the above solution will output "var is blank".

在用户必须指定扩展名或附加属性列表的情况下,未设置和设置为空字符串"之间的区别是必不可少的,并且不指定它们默认为非空值,而指定空字符串应使脚本使用空扩展名或附加属性列表.

The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.

尽管在每种情况下,这种区别可能并不重要.在这些情况下 [ -z "$var" ] 就可以了.

The distinction may not be essential in every scenario though. In those cases [ -z "$var" ] will be just fine.

这篇关于如何检查是否在 Bash 中设置了变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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