shell脚本中的if语句 shell脚本基本语法详解「建议收藏」

11/28 05:16:14 来源网站:辅助卡盟网

结果如图:

四.shell条件分支结构语句

1.单分支判断语句

格式:if 条件 ; then 结果 fi ,最后面一定要有fi,在shell脚本里面,控制分支结构结束都要和开头的单词相反辅助论坛,例如,if fi,case esac。

#!/bin/bash
echo "Please input a filename"
read filename
if [ -f $filename ];then
echo "this file is a ordinary file."
fi

结果如图:

2.双分支判断语句

echo "Please input a filename"
read filename
if [ -f $filename ];then
echo "this file is a ordinary file."
else
echo "this file is not a ordinary file."
fi

结果如图:

3.多分支判断语句

多分支判断有两种,和C语言的一样 if else if,case。只是形式上有一些不同。

#!/bin/bash
echo "Please input your math grades"

read grades
if [ $grades -gt 100 ] || [ $grades -lt 0 ];then
echo "Please input the number range in 0 - 100"
fi
if [ $grades -ge 90 ] && [ $grades -le 100 ];then
echo "Your grade is excellent."
elif [ $grades -ge 80 ] && [ $grades -le 89 ];then
echo "Your grade is good."
elif [ $grades -ge 70 ] && [ $grades -le 79 ];then
echo "Your grade is middle."
elif [ $grades -ge 60 ] && [ $grades -le 69 ];then
echo "Your grade is passing."
else
echo "Your grade is badly."
fi

结果如图:

#!/bin/bash
echo "Please input a command"
read cmd
case $cmd in
cpu)    echo "The cpu information is"
        cat  /proc/cpuinfo;;
mem)    echo "The mem information is"
        cat /proc/meminfo;;
device) echo "The device information is"
        cat /proc/scsi/device_info;;
CD-ROM) echo "The CD-ROM information is"
        cat /proc/sys/dev/cdrom/info;;
*)      echo "Your input command is invalid"
esac

结果如图:

五.shell循环语句

1.while语句

while语句是只要条件为真就执行下面语句。

格式:

while 条件

do

语句

done

需要注意的是,这里的条件除了 while true 可以这样写,其它的条件都要用 test或者 []来判断

    暂无相关资讯
shell脚本中的if语句 shell脚本基本语法详解「建议收藏」