bash 如何在 shell 脚本中声明和使用布尔变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2953646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:19:33  来源:igfitidea点击:

How can I declare and use Boolean variables in a shell script?

bashshellscriptingbooleansh

提问by hassaanm

I tried to declare a Boolean variable in a shell script using the following syntax:

我尝试使用以下语法在 shell 脚本中声明一个布尔变量:

variable=$false

variable=$true

Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?

这样对吗?另外,如果我想更新该变量,我会使用相同的语法吗?最后,以下将布尔变量用作表达式的语法是否正确?

if [ $variable ]

if [ !$variable ]

回答by miku

Revised Answer (Feb 12, 2014)

修订后的答案(2014 年 2 月 12 日)

the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
    echo 'Be careful not to fall off!'
fi


Original Answer

原答案

Caveats: https://stackoverflow.com/a/21210966/89391

注意事项:https: //stackoverflow.com/a/21210966/89391

the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
    echo 'Be careful not to fall off!'
fi

From: Using boolean variables in Bash

来自:在 Bash 中使用布尔变量

The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin trueon Jun 2, 2010 only applies to the original answer, not the revised.

之所以将原始答案包含在此处,是因为 2014 年 2 月 12 日修订前的评论仅与原始答案有关,并且与修订后的答案相关联时,许多评论是错误的。例如,丹尼斯·威廉姆森 (Dennis Williamson)true于 2010 年 6 月 2 日对内置 bash 的评论仅适用于原始答案,而不适用于修改后的答案。

回答by Dennis

TL;DR

TL; 博士

bool=true

if [ "$bool" = true ]


Issues with Miku's (original) answer

Miku(原始)答案的问题

I do notrecommend the accepted answer1. Its syntax is pretty, but it has some flaws.

推荐接受的答案1。它的语法很漂亮,但也有一些缺陷。

Say we have the following condition.

假设我们有以下条件。

if $var; then
  echo 'Muahahaha!'
fi

In the following cases2, this condition will evaluate to trueand execute the nested command.

在以下情况2 中,此条件将评估为true并执行嵌套命令。

# Variable var not defined beforehand. Case 1
var=''  # Equivalent to var="".        Case 2
var=    #                              Case 3
unset var  #                           Case 4
var='<some valid command>'  #          Case 5

Typically you only want your condition to evaluate to true when your "Boolean" variable, varin this example, is explicitly set to true. All the others cases are dangerously misleading!

通常,当您的“布尔”变量(var在本例中)显式设置为 true时,您只希望条件评估为 true。所有其他案例都是危险的误导!

The last case (#5) is especially naughty because it will execute the command contained in the variable (which is why the condition evaluates to true for valid commands3, 4).

最后一种情况(#5)特别顽皮,因为它将执行包含在变量中的命令(这就是为什么对于有效命令3, 4条件评估为真的原因)。

Here is a harmless example:

这是一个无害的例子:

var='echo this text will be displayed when the condition is evaluated'
if $var; then
  echo 'Muahahaha!'
fi

# Outputs:
# this text will be displayed when the condition is evaluated
# Muahahaha!

Quoting your variables is safer, e.g. if "$var"; then. In the above cases, you should get a warning that the command is not found. But we can still do better (see my recommendations at the bottom).

引用您的变量更安全,例如if "$var"; then. 在上述情况下,您应该收到未找到命令的警告。但是我们仍然可以做得更好(请参阅底部的我的建议)。

Also see Mike Holt's explanation of Miku's original answer.

另请参阅 Mike Holt 对 Miku 原始答案的解释。

Issues with Hbar's answer

有问题横条的答案

This approach also has unexpected behaviour.

这种方法也有意想不到的行为。

var=false
if [ $var ]; then
  echo "This won't print, var is false!"
fi

# Outputs:
# This won't print, var is false!

You would expect the above condition to evaluate to false, thus never executing the nested statement. Surprise!

您会期望上述条件评估为假,因此永远不会执行嵌套语句。惊喜!

Quoting the value ("false"), quoting the variable ("$var"), or using testor [[instead of [, do not make a difference.

引用值 ( "false")、引用变量 ( "$var") 或使用test[[代替[,都没有区别。

What I dorecommend:

建议:

Here are ways I recommend you check your "Booleans". They work as expected.

以下是我建议您检查“布尔值”的方法。它们按预期工作。

bool=true

if [ "$bool" = true ]; then
if [ "$bool" = "true" ]; then

if [[ "$bool" = true ]]; then
if [[ "$bool" = "true" ]]; then
if [[ "$bool" == true ]]; then
if [[ "$bool" == "true" ]]; then

if test "$bool" = true; then
if test "$bool" = "true"; then

They're all pretty much equivalent. You'll have to type a few more keystrokes than the approaches in the other answers5, but your code will be more defensive.

他们几乎都是等价的。与其他答案5 中的方法相比,您必须键入更多的按键,但您的代码将更具防御性。



Footnotes

脚注

  1. Miku's answer has since been edited and no longer contains (known) flaws.
  2. Not an exhaustive list.
  3. A valid command in this context means a command that exists. It doesn't matter if the command is used correctly or incorrectly. E.g. man womanwould still be considered a valid command, even if no such man page exists.
  4. For invalid (non-existent) commands, Bash will simply complain that the command wasn't found.
  5. If you care about length, the first recommendation is the shortest.
  1. Miku 的答案已被编辑,不再包含(已知)缺陷。
  2. 不是详尽的清单。
  3. 此上下文中的有效命令表示存在的命令。正确或错误地使用命令并不重要。例如man woman,即使不存在这样的手册页,仍将被视为有效命令。
  4. 对于无效(不存在)的命令,Bash 只会抱怨未找到该命令。
  5. 如果你关心长度,第一个建议是最短的。

回答by Mike Holt

There seems to be some misunderstanding here about the Bash builtin true, and more specifically, about how Bash expands and interprets expressions inside brackets.

这里似乎对 Bash builtin 存在一些误解true,更具体地说,关于 Bash 如何扩展和解释括号内的表达式。

The code in miku's answerhas absolutely nothing to do with the Bash builtin true, nor /bin/true, nor any other flavor of the truecommand. In this case, trueis nothing more than a simple character string, and no call to the truecommand/builtin is ever made, neither by the variable assignment, nor by the evaluation of the conditional expression.

代码中的三苦的答案有绝对无关,与Bash的内置true,也没有/bin/true,也没有任何其他的味道true命令。在这种情况下,true它只不过是一个简单的字符串,并且true不会通过变量赋值或条件表达式的评估调用命令/内置函数。

The following code is functionally identical to the code in the miku's answer:

以下代码在功能上与 miku 答案中的代码相同:

the_world_is_flat=yeah
if [ "$the_world_is_flat" = yeah ]; then
    echo 'Be careful not to fall off!'
fi

The onlydifference here is that the four characters being compared are 'y', 'e', 'a', and 'h' instead of 't', 'r', 'u', and 'e'. That's it. There's no attempt made to call a command or builtin named yeah, nor is there (in miku's example) any sort of special handling going on when Bash parses the token true. It's just a string, and a completely arbitrary one at that.

这里唯一的区别是被比较的四个字符是“y”、“e”、“a”和“h”,而不是“t”、“r”、“u”和“e”。就是这样。没有尝试调用命令或内置 named yeah,也没有(在 miku 的例子中)在 Bash 解析 token 时进行任何类型的特殊处理true。它只是一个字符串,并且是一个完全任意的字符串。

Update (2014-02-19):After following the link in miku's answer, now I see where some of the confusion is coming from. Miku's answer uses single brackets, but the code snippet he links to does not use brackets. It's just:

更新 (2014-02-19):按照 miku 回答中的链接之后,现在我看到了一些混乱的来源。Miku 的回答使用单括号,但他链接到的代码片段没有使用括号。只是:

the_world_is_flat=true
if $the_world_is_flat; then
  echo 'Be careful not to fall off!'
fi

Both code snippets will behavethe same way, but the brackets completely change what's going on under the hood.

两个代码片段的行为方式相同,但括号完全改变了幕后发生的事情。

Here's what Bash is doing in each case:

以下是 Bash 在每种情况下所做的:

No brackets:

没有括号:

  1. Expand the variable $the_world_is_flatto the string "true".
  2. Attempt to parse the string "true"as a command.
  3. Find and run the truecommand (either a builtin or /bin/true, depending on the Bash version).
  4. Compare the exit code of the truecommand (which is always 0) with 0. Recall that in most shells, an exit code of 0 indicates success and anything else indicates failure.
  5. Since the exit code was 0 (success), execute the ifstatement's thenclause
  1. 将变量$the_world_is_flat扩展为字符串"true"
  2. 尝试将字符串解析"true"为命令。
  3. 查找并运行true命令(内置命令或/bin/true,取决于 Bash 版本)。
  4. true命令的退出代码(始终为 0)与 0 进行比较。回想一下,在大多数 shell 中,退出代码 0 表示成功,其他任何内容表示失败。
  5. 由于退出代码为 0(成功),执行if语句的then子句

Brackets:

括号:

  1. Expand the variable $the_world_is_flatto the string "true".
  2. Parse the now-fully-expanded conditional expression, which is of the form string1 = string2. The =operator is bash's string comparisonoperator. So...
  3. Do a string comparison on "true"and "true".
  4. Yep, the two strings were the same, so the value of the conditional is true.
  5. Execute the ifstatement's thenclause.
  1. 将变量$the_world_is_flat扩展为字符串"true"
  2. 解析现在完全展开的条件表达式,其形式为string1 = string2。该=操作是bash的字符串比较操作符。所以...
  3. "true"和进行字符串比较"true"
  4. 是的,两个字符串是相同的,所以条件的值为真。
  5. 执行if语句的then子句。

The no-brackets code works, because the truecommand returns an exit code of 0, which indicates success. The bracketed code works, because the value of $the_world_is_flatis identical to the string literal trueon the right side of the =.

无括号代码有效,因为该true命令返回退出代码 0,这表示成功。括号内的代码工作,因为价值$the_world_is_flat是相同的字符串文字true上的右侧=

Just to drive the point home, consider the following two snippets of code:

为了说明这一点,请考虑以下两个代码片段:

This code (if run with root privileges) will reboot your computer:

此代码(如果以 root 权限运行)将重新启动您的计算机:

var=reboot
if $var; then
  echo 'Muahahaha! You are going down!'
fi

This code just prints "Nice try." The reboot command is not called.

此代码仅打印“Nice try”。不调用重启命令。

var=reboot
if [ $var ]; then
  echo 'Nice try.'
fi

Update (2014-04-14)To answer the question in the comments regarding the difference between =and ==: AFAIK, there is no difference. The ==operator is a Bash-specific synonym for =, and as far as I've seen, they work exactly the same in all contexts.

更新(2014年4月14日)要回答在评论有关之间的差异问题===:据我所知,没有任何区别。该==运营商是一个Bash的专用代名词=,而据我所看到的,他们的工作在所有情况完全一样。

Note, however, that I'm specifically talking about the =and ==string comparison operators used in either [ ]or [[ ]]tests. I'm not suggesting that =and ==are interchangeable everywherein bash.

但是请注意,我专门讨论在或测试中使用的===字符串比较运算符。我不是建议这样做,并且在 bash 中的任何地方都可以互换。[ ][[ ]]===

For example, you obviously can't do variable assignment with ==, such as var=="foo"(well technically you cando this, but the value of varwill be "=foo", because Bash isn't seeing an ==operator here, it's seeing an =(assignment) operator, followed by the literal value ="foo", which just becomes "=foo").

例如,您显然不能用 进行变量赋值==,例如var=="foo"(从技术上讲,您可以这样做,但是varwill的值是"=foo",因为 Bash==在这里没有看到运算符,它看到的是=(赋值)运算符,然后字面值="foo",它只是变成"=foo")。

Also, although =and ==are interchangeable, you should keep in mind that how those tests work doesdepend on whether you're using it inside [ ]or [[ ]], and also on whether or not the operands are quoted. You can read more about that in Advanced Bash Scripting Guide: 7.3 Other Comparison Operators(scroll down to the discussion of =and ==).

此外,虽然===可以互换,但您应该记住,这些测试的工作方式取决于您是否在[ ]或 中使用它[[ ]],以及操作数是否被引用。你可以阅读更多有关在高级Bash脚本编程指南:7.3其他比较操作符(向下滚动到的讨论===)。

回答by Quolonel Questions

Use arithmetic expressions.

使用算术表达式。

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true

Output:

输出:

true
not false


不假

回答by Hubert Grzeskowiak

Long story short:

长话短说:

There are no Booleans in Bash

Bash 中没有布尔值

Bash does have Boolean expressions in terms of comparison and conditions. That said, what you can declare and compare in Bash are strings and numbers. That's it.

Bash 在比较和条件方面确实有布尔表达式。也就是说,您可以在 Bash 中声明和比较的是字符串和数字。就是这样。

Wherever you see trueor falsein Bash, it's either a string or a command/builtin which is only used for its exit code.

无论您在何处truefalse在 Bash 中看到,它都是字符串或命令/内置命令,仅用于其退出代码。

This syntax...

这个语法...

if true; then ...

is essentially...

本质上是...

if COMMAND; then ...

The condition is true whenever the command returns exit code 0. trueand falseare Bash builtins and sometimes also standalone programs that do nothing but returning the corresponding exit code.

每当命令返回退出代码 0 时,条件为真。true并且false是 Bash 内置程序,有时也是独立程序,除了返回相应的退出代码之外什么都不做。

The conditional above is equivalent to:

上面的条件等效于:

COMMAND && ...


When using square brackets or the testcommand, you rely on the exit code of that construct. Keep in mind that [ ]and [[ ]]are also just commands/builtins like any other. So ...

使用方括号或test命令时,您依赖于该构造的退出代码。请记住,[ ][[ ]]其他命令一样也只是命令/内置函数。所以 ...

if [[ 1 == 1 ]]; then echo yes; fi

corresponds to

对应于

if COMMAND; then echo yes; fi

and the COMMANDhere is [[ 1 == 1 ]]

COMMAND这里是[[ 1 == 1 ]]

The if..then..ficonstruct is just syntactic sugar. You can always just run the commands separated by a double ampersand for the same effect:

if..then..fi构造只是语法糖。您始终可以运行由双与号分隔的命令以获得相同的效果:

[[ 1 == 1 ]] && echo yes

When using trueand falsein these testing constructs you are actually only passing the string "true"or "false"to the testing command. Here is an example:

当使用true以及false在这些测试结构,实际上是只传递字符串"true""false"到测试命令。下面是一个例子:

Believe it or not but those conditions are all yielding the same result:

信不信由你,但这些条件都产生相同的结果

if [[ false ]]; then ...
if [[ "false" ]]; then ...
if [[ true ]]; then ...
if [[ "true" ]]; then ...

TL;DR; always compare against strings or numbers

TL; 博士; 始终与字符串或数字进行比较

To make this clear to future readers, I would recommend always using quotes around trueand false:

为了让未来的读者清楚这一点,我建议始终在true和周围使用引号false

DO

if [[ "${var}" == "true" ]]; then ...
if [[ "${var}" == "false" ]]; then ...
if [[ -n "${var:-}" ]]; then echo "var is not empty" ...

DON'T

if [ ... ]; then ...  # Always use double square brackets in bash!
if [[ "${var}" ]]; then ...  # This is not as clear or searchable as -n
if [[ "${var}" != true ]]; then ...  # Creates impression of Booleans
if [[ "${var}" -eq "true" ]]; then ...  # `-eq` is for numbers and doesn't read as easy as `==`

Maybe

也许

if [[ "${var}" != "true" ]]; then ...  # Creates impression of Booleans. It can be used for strict checking of dangerous operations. This condition is false for anything but the literal string "true".

回答by Hbar

Long ago, when all we had was sh, Booleans where handled by relying on a convention of the testprogram where testreturns a false exit status if run without any arguments.

很久以前,当我们只有sh, Booleans 时,依赖于test程序的约定来处理,test如果不带任何参数运行,则返回错误的退出状态。

This allows one to think of a variable that is unset as false and variable set to any value as true. Today, testis a builtin to Bash and is commonly known by its one-character alias [(or an executable to use in shells lacking it, as dolmen notes):

这允许人们将未设置为 false 的变量和设置为任何值的变量视为 true。今天,它test是 Bash 的内置函数,通常以其单字符别名[(或在缺少它的 shell 中使用的可执行文件,如 dolmen 所言)而广为人知:

FLAG="up or <set>"

if [ "$FLAG" ] ; then
    echo 'Is true'
else
    echo 'Is false'
fi

# Unset FLAG
#    also works
FLAG=

if [ "$FLAG" ] ; then
    echo 'Continues true'
else
    echo 'Turned false'
fi

Because of quoting conventions, script writers prefer to use the compound command [[that mimics test, but has a nicer syntax: variables with spaces do not need to be quoted; one can use &&and ||as logical operators with weird precedence, and there are no POSIX limitations on the number of terms.

由于引用约定,脚本编写者更喜欢使用[[模仿的复合命令test,但具有更好的语法:带空格的变量不需要被引用;可以使用&&and||作为具有奇怪优先级的逻辑运算符,并且对术语的数量没有 POSIX 限制。

For example, to determine if FLAG is set and COUNT is a number greater than 1:

例如,要确定是否设置了 FLAG 并且 COUNT 是大于 1 的数字:

FLAG="u p"
COUNT=3

if [[ $FLAG  && $COUNT -gt '1' ]] ; then
    echo 'Flag up, count bigger than 1'
else
    echo 'Nope'
fi

This stuff can get confusingwhen spaces, zero length strings, and null variables are all needed and also when your script needs to work with several shells.

当所有需要空格、零长度字符串和空变量时,以及当您的脚本需要使用多个 shell 时,这些东西可能会令人困惑

回答by sjsam

How can I declare and use Boolean variables in a shell script?

如何在 shell 脚本中声明和使用布尔变量?

Unlike many other programming languages, Bash does not segregate its variables by "type." [1]

与许多其他编程语言不同,Bash 不按“类型”分隔其变量。[1]

So the answer is pretty clear. There isn't any Boolean variablein Bash.

所以答案很明确。Bash 中没有任何布尔变量

However:

然而:

Using a declare statement, we can limit the value assignment to variables.[2]

使用声明语句,我们可以限制对变量的赋值。[2]

#!/bin/bash
declare -ir BOOL=(0 1) # Remember BOOL can't be unset till this shell terminates
readonly false=${BOOL[0]}
readonly true=${BOOL[1]}

# Same as declare -ir false=0 true=1
((true)) && echo "True"
((false)) && echo "False"
((!true)) && echo "Not True"
((!false)) && echo "Not false"

The roption in declareand readonlyis used to state explicitly that the variables are readonly. I hope the purpose is clear.

r选件declarereadonly用于国家明确的变量是只读的。我希望目的很明确。

回答by Pyrolistical

Instead of faking a Boolean and leaving a trap for future readers, why not just use a better value than true and false?

与其伪造布尔值并为未来的读者留下陷阱,为什么不使用比 true 和 false 更好的值呢?

For example:

例如:

build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

回答by LinuxSecurityFreak

POSIX(Portable Operating System Interface)

POSIX(便携式操作系统接口)

I miss here the key point, which is portability. That's why my header has POSIXin itself.

我在这里错过了关键点,即便携性。这就是为什么我的标题本身具有POSIX

Essentially, all of the voted answers are correct, with the exception they are Bash-specific too much.

本质上,所有投票的答案都是正确的,除了它们是Bash特定的太多。

Basically, I only wish to add more information about portability.

基本上,我只想添加更多关于便携性的信息。



  1. [and ]brackets like in [ "$var" = true ]are not necessary, and you can omit them and use the testcommand directly:

    test "$var" = true && yourCodeIfTrue || yourCodeIfFalse
    

    Important note: I no longer recommend thisas it's being slowly deprecated and more difficult to combine multiple statements.

  2. Imagine what those words trueand falsemean to the shell, test it yourself:

    echo $(( true ))
    
    0
    
    echo $(( false ))
    
    1
    

    But using quotes:

    echo $(( "true" ))
    
    bash: "true": syntax error: operand expected (error token is ""true"")
    sh (dash): sh: 1: arithmetic expression: expecting primary: ""true""
    

    The same goes for:

    echo $(( "false" ))
    

    The shell can't interpret it other than a string. I hope you are getting the idea of how good it is using proper keyword without quotes.

    But no one said it in previous answers.

  3. What does this mean? Well, several things.

    • You should get used to the Boolean keywords are actually treated like numbers, that is true= 0and false= 1, remember all non-zero values are treated like false.

    • Since they are treated as numbers, you should treat them like that too, i.e. if you define variable say:

      var_bool=true
      echo "$var_bool"
      
       true
      

      you can create an opposite value of it with:

      var_bool=$(( 1 - $var_bool ))  # same as $(( ! $var_bool ))
      echo "$var_bool"
      
      1
      

    As you can see for yourself, the shell does print truestring for the first time you use it, but since then, it all works via number 0representing trueor 1representing false, respectively.

  1. []in 之[ "$var" = true ]类的括号不是必须的,你可以省略它们并test直接使用命令:

    test "$var" = true && yourCodeIfTrue || yourCodeIfFalse
    

    重要提示:我不再推荐这个,因为它正在慢慢被弃用,并且更难以组合多个语句。

  2. 想象一下那些话true,并false指到外壳,测试自己:

    echo $(( true ))
    
    0
    
    echo $(( false ))
    
    1
    

    但是使用引号:

    echo $(( "true" ))
    
    bash: "true": syntax error: operand expected (error token is ""true"")
    sh (dash): sh: 1: arithmetic expression: expecting primary: ""true""
    

    这同样适用于:

    echo $(( "false" ))
    

    除了字符串之外,shell 无法解释它。我希望您了解使用不带引号的正确关键字有多好。

    但是在之前的答案中没有人说过。

  3. 这是什么意思?嗯,有几件事。

    • 您应该习惯布尔关键字实际上被视为数字,即true=0false= 1,请记住所有非零值都被视为false

    • 由于它们被视为数字,因此您也应该这样对待它们,即如果您定义变量说:

      var_bool=true
      echo "$var_bool"
      
       true
      

      您可以使用以下方法创建相反的值:

      var_bool=$(( 1 - $var_bool ))  # same as $(( ! $var_bool ))
      echo "$var_bool"
      
      1
      

    正如您自己所看到的,shell 在true您第一次使用它时会打印string,但从那时起,它都分别通过 number 0representationtrue1representationfalse工作。



Finally, what you should do with all that information

最后,您应该如何处理所有这些信息

  • First, one good habit would be assigning 0instead of true; 1instead of false.

  • Second good habit would be to test if the variable is / isn't equal to zero:

    if [ "$var_bool" -eq 0 ]; then
         yourCodeIfTrue
    else
         yourCodeIfFalse
    fi
    
  • 首先,一个好习惯是赋值0而不是true; 1而不是false.

  • 第二个好习惯是测试变量是否/不等于零:

    if [ "$var_bool" -eq 0 ]; then
         yourCodeIfTrue
    else
         yourCodeIfFalse
    fi
    

回答by Eric P

Regarding syntax, this is a simple methodology that I use (by example) to consistently and sanely manage Boolean logic:

关于语法,这是一种简单的方法,我使用它(通过示例)来一致而理智地管理布尔逻辑:

# Tests
var=
var=''
var=""
var=0
var=1
var="abc"
var=abc

if [[ -n "${var}" ]] ; then
    echo 'true'
fi
if [[ -z "${var}" ]] ; then
    echo 'false'
fi

# Results
# var=        # false
# var=''      # false
# var=""      # false
# var=0       # true
# var=1       # true
# var="abc"   # true
# var=abc     # true

If the variable is never declared the answer is: # false

如果从未声明变量,则答案是: # false

So, a simple way to set a variable to true (using this syntax methodology) would be, var=1; conversely, var=''.

所以,一个简单的方法给一个变量设置为true(使用此语法的方法)将是var=1; 反之,var=''

Reference:

参考:

-n= True if the length of var string is non-zero.

-n= 如果 var 字符串的长度非零,则为真。

-z= True if the length of var string is zero.

-z= 如果 var 字符串的长度为零,则为真。