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

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

问题描述

&&||-a-o 有什么区别> Unix 运算符?

What is 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?

如:

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

对比:

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

推荐答案

经验法则: 在正方形内使用 -a-o括号,&&|| 外面.

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

了解 shell 语法和 [ command 语法之间的区别很重要.

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

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

  • && 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.

[ 不是特殊语法.它实际上是一个名为 [ 的命令,也称为 test.由于 [ 只是一个普通命令,它使用 -a-o 作为它的 and 运算符.它不能使用 &&|| 因为它们是命令看不到的 shell 语法.

[ 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.

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

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天全站免登陆