[ 实际上是一个命令。执行ls /bin/[ 或ls /usr/bin/[。你会看到它实际上是一个可执行文件。
[...] 来自旧的 Bourne shell 时代。 if 命令执行该语句,如果该语句的退出代码为零,则该语句被视为 true 并执行 if 子句。如果退出代码不为零,则执行 else 子句(如果存在)。
试试这些:
$ date
Fri May 18 00:04:03 EDT 2012
echo $? #Prints the exit code of the date command
0
$ date -Q #Shouldn't work, I hope...
date: illegal option -- q
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
$ echo $? #Exit code for the date command
1
您可以看到date 是一个有效命令并返回退出代码0($? 的值),但date -Q 无效,并返回退出代码1。
现在让我们在if 语句中尝试一下:
if date
then
echo "I've successfully printed out the date!"
else
echo "I made a mistake in the command"
fi
现在试试这个:
if date -q
then
echo "I've successfully printed out the date!"
else
echo "I made a mistake in the command"
fi
最初,[...] 是test 命令的别名。以下是等价的:
if test -f /bin/ls #Does a file called /bin/ls exist?
then
echo "There's a /bin/ls file"
fi
和
if [ -f /bin/ls ]
then
echo "There's a /bin/ls file"
fi
这就是为什么在[ 和] 周围放置空格非常重要。因为这些实际上是命令。在 BASH 中,shell 内置,但它们是命令。这也是为什么所有测试参数(如-f、-z 和-eq)都以破折号为前缀的原因。它们最初是test 命令的参数。