加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash:简单if语句

发布时间:2020-12-15 18:29:00 所属栏目:安全 来源:网络整理
导读:参见英文答案 How do I compare two string variables in an ‘if’ statement in Bash?12个 我的问题可以简化为使以下脚本工作(需要1个命令行参数): #!/bin/bashif ["$1" == "0"]; then echo "good"else echo "bad"fi 当我运行脚本0时,这应该打印好,但我无
参见英文答案 > How do I compare two string variables in an ‘if’ statement in Bash?12个
我的问题可以简化为使以下脚本工作(需要1个命令行参数):
#!/bin/bash
if ["$1" == "0"]; then
    echo "good"
else
    echo "bad"
fi

当我运行脚本0时,这应该打印好,但我无法得到它.我尝试了各种数字的引号组合,我尝试过=,==和-eq.那么…… bash,它是如何运作的?

[实际上是一个命令.做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

最初,[…]是测试命令的别名.以下是等效的:

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)都以短划线为前缀的原因.它们最初是测试命令的参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读