1818a109388e

shell中的if主要是用于程序的判断逻辑,从而控制脚本的执行逻辑。这和很多编程语言思路上都是一致的。

1、if的用法结构如下:

if exp;then

command1;

command2;

fi

示例:

#根据输入的学生成绩打印对应的成绩等级:大于90分为优秀;大于80分良好,60到80分为及格;小于60分为差。

cat test.sh

#!/bin/bash

read -p "请输入分数:" Score

if [ "$Score" -ge 90 ]; then

echo "优秀"

fi

if [ "$Score" -ge 80 ]; then

echo "良好"

fi

if [ "$Score" -ge 60 -a "$Score" -lt 80 ]; then

echo "及格"

fi

if [ "$Score" -lt 60 ]; then

echo "差"

fi

运行如下:输入:88

输出:良好

输入:99

输出:优秀

2、if/else结构用法

语法结构:

if exp; then

command

else

command

fi

示例:#判断某个文件是否存在

cat checkfile.sh

脚本内容如下:

#!/bin/bash

fl=/root/hgm/bash.sh

f2=/root/hgm/bash00.sh

if [ -e $f1 ];then

echo "$f1 存在"

else

echo "$f1 不存在"

fi

if [ -e $f2 ];then

echo "$f2 存在"

else

echo "$f2 不存在"

fi

bash checkfile.sh

输出结果:

存在

/root/hgm/bash00.sh 不存在

2、if/elif/else结构用法

语法格式:

if exp1; then

command1

elseif exp2;then

command2

elseif exp3;then

command3

...

fi

具体用法和上面两种很相似不再举例说明

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐