Bash中的布尔运算符(&&amp ;、 -a,||,-o) [英] Boolean operators ( &&, -a, ||, -o ) in Bash

查看:154
本文介绍了Bash中的布尔运算符(&&amp ;、 -a,||,-o)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释&&||-a-o Unix运算符之间的区别吗?

两种类型的使用都有哪些限制?

在这种情况下使用标志时,是否应该简单地使用&&||运算符?

如:

[ "$1" = "yes" ] && [ -r $2.txt ]

与之相对:

[ "$1" = "yes" -a $2 -lt 3 ]

解决方案

经验法则:在方括号内使用-a-o,在方括号内使用&&||. /p>

重要的是要了解 shell 语法和[ 命令的语法之间的区别.

  • &&||是shell运算符.它们用于合并两个命令的结果.因为它们是shell语法,所以它们具有特殊的语法意义,因此不能用作命令的参数.

  • [不是特殊语法.它实际上是一个名为[的命令,也称为test.由于[只是一个常规命令,因此将-a-o用于其运算符.它不能使用&&||,因为那些是命令看不到的shell语法.

但是等等! Bash具有[[ ]]形式的更高级的测试语法.如果使用双方括号,则可以访问正则表达式和通配符.您也可以在括号内自由使用&&||<>之类的shell运算符,因为与[不同,双括号形式特殊的shell语法. Bash解析[[本身,因此您可以编写[[ $foo == 5 && $bar == 6 ]]之类的东西.

Can someone please explain the difference between the &&, ||, -a, and -o Unix operators?

What are the restrictions on the usage of both types?

Is it simply that the && and || operators should be used when using flags in the condition?

As in:

[ "$1" = "yes" ] && [ -r $2.txt ]

versus:

[ "$1" = "yes" -a $2 -lt 3 ]

解决方案

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

这篇关于Bash中的布尔运算符(&amp;&amp ;、 -a,||,-o)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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