什么是[和[[在bash有什么区别? [英] What's the difference between [ and [[ in bash?

查看:158
本文介绍了什么是[和[[在bash有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了看bash的手册页和 [表示,使用条件前pressions。然后我看着有条件防爆pressions部分,它列出了相同的运营商为测试(和 [)。

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脚本。我最喜欢的是:

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


  1. 这是shell的语法特点,所以它有一些特殊的行为 [没有。你不再需要引用拼了命变量,因为 [处理空字符串和字符串用空格更直观。例如, [你写

  1. 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 ]]


  • 由于它是一个语法功能,它可以让您使用&放大器;&安培; || 布尔测试和&LT运营商; > 字符串比较。 [不能做到这一点,因为这是一个普通的命令和&放大器;&安培; || < > 不传递到常规命令作为命令行参数。

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

    它有一个美好的 =〜运营商定期做前pression匹配。随着 [你可以写

    It has a wonderful =~ operator for doing regular expression matches. With [ you might write

    if [ "$ANSWER" = y -o "$ANSWER" = yes ]
    

    使用 [你可以这样写为

    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什么。一应俱全:

    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兼容的脚本,那么你需要坚持使用 [。确保您已在#!/斌/庆典家当您的脚本行,如果你使用双括号。

    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 FAQ - "What is the difference between test, [ and [[ ?"
    • Bash Practices - Bash Tests
    • Server Fault - What is the difference between double and single brackets in bash?

    这篇关于什么是[和[[在bash有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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