Bash 中的 [ 和 [[ 有什么区别? [英] What's the difference between [ and [[ in Bash?
问题描述
我查看了 bash 手册页,[[
说它使用条件表达式.然后我查看了条件表达式部分,它列出了与 test
(和 [
)相同的运算符.
I looked at bash man page and the [[
says it uses Conditional Expressions. Then I looked at Conditional Expressions section and it lists the same operators as test
(and [
).
所以我想知道,[
和 [[
在 Bash 中有什么区别?
So I wonder, what is the difference between [
and [[
in Bash?
推荐答案
[[
是 bash 对 [
命令的改进.如果您编写针对 bash 的脚本,它具有多项增强功能,使其成为更好的选择.我最喜欢的是:
[[
is bash's improvement to the [
command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:
它是 shell 的一个语法特性,所以它有一些
[
没有的特殊行为.您不再需要像 mad 一样引用变量,因为[[
可以更直观地处理空字符串和带有空格的字符串.例如,使用[
你必须写
It is a syntactical feature of the shell, so it has some special behavior that
[
doesn't have. You no longer have to quote variables like mad because[[
handles empty strings and strings with whitespace more intuitively. For example, with[
you have to write
if [ -f "$file" ]
正确处理空字符串或包含空格的文件名.使用 [[
引号是不必要的:
to correctly handle empty strings or file names with spaces in them. With [[
the quotes are unnecessary:
if [[ -f $file ]]
因为它是一个语法特性,所以它允许您使用 &&
和 ||
运算符进行布尔测试和 <
和 >
用于字符串比较.[
不能这样做,因为它是一个常规命令,&&
, ||
, <
,和 >
不会作为命令行参数传递给常规命令.
Because it is a syntactical feature, it lets you use &&
and ||
operators for boolean tests and <
and >
for string comparisons. [
cannot do this because it is a regular command and &&
, ||
, <
, and >
are not passed to regular commands as command-line arguments.
它有一个很棒的 =~
操作符来进行正则表达式匹配.使用 [
你可能会写
It has a wonderful =~
operator for doing regular expression matches. With [
you might write
if [ "$answer" = y -o "$answer" = yes ]
使用 [[
你可以把它写成
With [[
you can write this as
if [[ $answer =~ ^y(es)?$ ]]
它甚至可以让您访问它存储在 BASH_REMATCH
中的捕获组.例如,如果您在上面输入完整的是",${BASH_REMATCH[1]}
将是es".
It even lets you access the captured groups which it stores in BASH_REMATCH
. For instance, ${BASH_REMATCH[1]}
would be "es" if you typed a full "yes" above.
您可以免费获得模式匹配又名通配.也许您对如何输入 yes 不那么严格.如果用户输入 y-anything,也许你没问题.满足您的需求:
You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:
if [[ $ANSWER = y* ]]
请记住,它是一个 bash 扩展,因此如果您正在编写与 sh 兼容的脚本,那么您需要坚持使用 [
.如果您使用双括号,请确保您的脚本有 #!/bin/bash
shebang 行.
Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [
. Make sure you have the #!/bin/bash
shebang line for your script if you use double brackets.
这篇关于Bash 中的 [ 和 [[ 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!