我的问题可以简化为使以下脚本工作(需要1个命令行参数):
#!/bin/bash
if ["$1" == "0"]; then
echo "good"
else
echo "bad"
fi
当我运行脚本0 时,应该打印好,但我无法理解。我尝试了各种数字的引号组合,我尝试过=,==和-eq。那么...... bash,它是如何运作的?
答案 0 :(得分:17)
[
实际上是一个命令。执行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
命令的参数。
答案 1 :(得分:13)
在括号和参数
之间使用空格$ cat x
#!/bin/bash
if [ "$1" == "0" ]; then
echo "good"
else
echo "bad"
fi
$ bash x 0
good
答案 2 :(得分:11)
使用双括号进行算术比较,然后您不必担心引号和间距,例如:
#!/bin/bash
if (($1 == 0)); then
echo "good"
else
echo "bad"
fi
一般规则:对算术使用(( ))
,对文本和模式使用[[ ]]
正如其他人所说的那样,[旧的Bourne shell语法并没有什么理由再次使用它了。