一个简单的"if"语句 [英] A simple 'if' statement

查看:110
本文介绍了一个简单的"if"语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题可以简化为使以下脚本正常工作(需要一个命令行参数):

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屋!

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