[]在bash中做什么?

What does [] do in bash?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
bash: double or single bracket, parentheses, curly braces

查看archlinux中的rc.dcron脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
. /etc/rc.conf
. /etc/rc.d/functions

name=crond
. /etc/conf.d/crond
PID=$(pidof -o %PPID /usr/sbin/crond)

case"$1" in
start)
    stat_busy"Starting $name daemon"
    [[ -z"$PID" ]] && /usr/sbin/crond $CRONDARGS &>/dev/null \
    && { add_daemon $name; stat_done; } \
    || { stat_fail; exit 1; }
    ;;

虽然我能找出大多数语法,但这到底是做什么的:

1
 [[ -z"$PID" ]]

我看到它也写了:

1
 [ -z"$PID" ]

在参考文献中,我发现if语句中使用了[],但这里没有看到。任何帮助都非常感谢。谢谢!


左括号([)是test命令的别名,它执行所有测试,并返回0表示真或其他值表示假。"if"只对测试命令的返回值作出反应。右括号告诉测试表达式的结束位置。双括号([)是一个内置的bash,可以替换外部的测试调用。


单括号模拟了一个旧的Unix实用程序/usr/bin/test。他们按你的要求做,但不是你想要的。双括号是改进的,这是bash特有的。

http://tldp.org/ldp/abs/html/testconstructs.html_dblbrackets

There exists a dedicated command called [ (left bracket special character). It is a synonym for test, and a builtin for efficiency reasons. This command considers its arguments as comparison expressions or file tests and returns an exit status corresponding to the result of the comparison (0 for true, 1 for false).

With version 2.02, Bash introduced the [[ ... ]] extended test command, which performs comparisons in a manner more familiar to programmers from other languages. Note that [[ is a keyword, not a command.

No filename expansion or word splitting takes place between [[ and ]], but there is parameter expansion and command substitution.

Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct.


根据本手册:

Brackets to return a binary result of expression: [[ ]]

[[ expression ]]

Return a status of 0 or 1 depending on the evaluation of the conditional expression. Word splitting and filename expansion are not performed on the words between the [[' and]]'; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution,
process substitution, and quote removal are performed.

The && and || commands do not execute expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.