一个简单的"if"语句 [英] A simple 'if' statement
问题描述
我的问题可以简化为使以下脚本正常工作(需要一个命令行参数):
My problem can be simplified down to making the following script work (which takes one command line argument):
#!/bin/bash
if ["$1" == "0"]; then
echo "good"
else
echo "bad"
fi
当我运行脚本0 时,这应该打印好,但我无法理解.我已经尝试过用引号引起来的各种组合,还尝试过=,==和-eq.那么... bash,它是如何工作的?
This should print good when I run script 0, but I can't get it to. I've tried various combinations of quotes around the numbers, and I've tried =, ==, and -eq. So... bash, how does it work?
推荐答案
[
实际上是一个命令.进行ls /bin/[
或ls /usr/bin/[
.您会看到它实际上是一个可执行文件.
The [
is actually a command. Do a ls /bin/[
or an ls /usr/bin/[
. You'll see it's actually an executable file.
[...]
来自古老的伯恩贝壳时代. if
命令执行该语句,如果该语句的退出代码为零,则将该语句视为 true 并执行if子句.如果退出代码不为零,则执行else子句(如果存在).
The [...]
is from the old Bourne shell days. The if
command executes the statement, and if the exit code of that statement is a zero, the statement is considered true and the if clause is executed. If the exit code is not zero, the else clause is executed (if present).
尝试以下方法:
$ 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.
You can see that date
is a valid command and returns an exit code of 0 (the value of $?
), but date -Q
isn't valid, and returns an exit code of 1.
现在让我们在if
语句中尝试它们:
Now let's try them in the if
statement:
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
命令的别名.以下是等效的:
Originally, the [...]
was an alias for the test
command. The following are equivalent:
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
命令的参数.
This is why it's very important to put spaces around the [
and ]
. Because these are actually commands. In BASH, there's built into the shell, but they are commands. That's also why all the test parameters (things like -f
, -z
, and -eq
) all are prefixed with dashes. They were originally parameters for the test
command.
这篇关于一个简单的"if"语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!