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

查看:17
本文介绍了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?

是不是简单的&&||操作符在条件中使用flags时应该使用?

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