当前位置: 代码网 > 服务器>服务器>Linux > bash shell的条件语句详解

bash shell的条件语句详解

2025年02月13日 Linux 我要评论
~ script% touch if.sh~ script% chmod 755 if.sh1.if-then-fi#!/usr/bin/env bashfood=$1if [ $food="appl
~ script% touch if.sh
~ script% chmod 755 if.sh

1.if-then-fi

#!/usr/bin/env bash
food=$1
if [ $food="apple" ]
then
	echo the food is $food
fi
exit 0
~ script % ./if.sh apple
the food is apple

如果要将多条语句写在一行,可以分号分割开,如:

if [ $food="apple" ];then

注意:
if [ 条件 ],中括号包住的条件与括号之间必须要有空格。if关键字与中括号之间也必须要有空格。为什么会这样, 因为命令与参数之间必须要用空格分开。[]中括号代表的量test这个命令,所以上面的if语句也可以写成:

if test $food="apple"
then
        echo the food is $food
fi

所以如果没有空格了,解析器就会找到一个错误或不存在的命令,因为它会把在每一行遇到的第一个空格前面有字符串的字符串当作是命令,之后的当作是参数。所以如果if和[]没有空格,执行脚本时就会报错,把if[ apple=apple ]都当作是命令了,而这实际上是一个不存在的命令:

~ script % ./if.sh apple
./if.sh: line 4: if[ apple=apple ]: command not found

温馨提示:赋值语句的等号左右不能有空格,否则会报错。

2.else子句

if.sh:

#!/usr/bin/env bash
num=$1
if [ $num -eq 10 ] # = 等价于-eq,后者只能用于数字的比较上,前者=,则在字符串和数字上都能用于相等的比较
then
        echo it is 10
else
        echo it is not 10
fi
exit 0
~ script % ./if.sh 109
it is not 10

3.elif子句

#!/usr/bin/env bash
num=$1
if [ $num -eq 10 ] # = 等于-eq,后者只能用于数字的比较上,前者则都可以用在字符串和数字的相等比较上
then
        echo equal 10
elif [ $num -lt 10 ]
then
        echo less than 10
elif [ $num -le 11 ]
then
        echo less than or equal 11
else
        echo greater than 11
fi
exit 0
~ script % ./if.sh 109
greater than 11

-eq:equal 等于-lt:less than 小于-gt:greater than 大于-le:less than or equal 小于或等于-ge:greater than or equal 大于或等于

为什么不可以用<,>等来表达上面这些关系,因为这些符号在类unix系统中有特殊用途。

到此这篇关于bash shell的条件语句的文章就介绍到这了,更多相关bash shell条件语句内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com