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

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

问题描述

我怎么知道,如果一个变量在Bash的设置?

例如,我该如何检查,如果用户给出的第一个参数的函数吗?

 功能{
    ??如果$ 1设置
}


解决方案

的正确方法

 如果[-z $ {VAR + X}];然后回声无功未设置;其他回声无功被设置为$ VAR';科幻

其中, $ {VAR + X} 是<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02\">parameter扩展其计算结果为空,如果 VAR 没有设置并替换字符串 X ,否则

,然后在那里引号可以省略(所以在这里说,我们可以说 $ {VAR + X} 而不是$ {VAR + X}),因为这种语法和放大器;使用保证这只会扩大​​到一些不需要引号(如,因为它要么扩大到 X (其中不包含断字因此它需要不带引号),或没有(这导致在 [-z] 这也得心应手计算结果为相同的值(真)为 [-z] 做)),但作为事实上的报价可以在这里放心地省略不会立即有目共睹(实际上,它是不是的的第一作者引用的解释谁也是一大猛砸codeR),它有时会比较好写与报价的解决方案,因为 [-z$ {VAR + X }] 在非常小的O可能涉及的费用(1)速度的损失,或/和(第一作者做了什么:)旁边使用此解决方案的code加注释给网址该答案现在还包括为何引号可以安全地省略其说明。

错误的方式

 如果[-z$ VAR];然后回声无功未设置;其他回声无功被设置为$ VAR';科幻

这是因为它不变量是未设置,并且被设置为空字符串的变量之间进行区分。也就是说,如果 VAR ='',那么上述方案将错误地输出无功未设置。

但是,这区别是在用户具有指定的延伸,或属性的附加列表的情况下必需的,并且不指定他们默认为一个非空值,而指定空字符串应使脚本用空扩展或附加属性列表。

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
}

解决方案

The right way

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

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

and then where the quotes can be omitted (so here say we can say ${var+x} instead of "${var+x}") because this syntax & usage guarantees this will only expand to something not needing quotes (as since it either expands to x (which contains no word breaks so it needs no quotes) or to nothing (which results in [ -z ] which handily also evaluates to the same value (true) as [ -z "" ] does)), however as the fact the quotes can be safely omitted here is not immediately obvious to all (indeed it wasn't 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 possible cost of very small O(1) speed penalty, or/and (what the first author did:) next to the code using this solution put a comment giving the URL to this answer which now also includes the explanation for why the quotes can be safely omitted.

The wrong way

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

This is 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 incorrectly output that var is unset.

But this distinction 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.

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

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