通过几个案例掌握shell编程条件分支结构

shell脚本是任何一个后端程序员都应该去掌握的技能,今天,我们来一起学习下它的条件分支结构,然后通过几个案例去掌握它。

首先,我们来看shell脚本的基本结构,基本结构如下:

#!/bin/bash

代码

下面,我们来编写一个最简单的shell脚本程序吧。

#!/bin/bash

echo 'hello world'

当上面程序执行后,就会在屏幕上打印出hello world字符。

接下来,我们再来看看条件分支结构,shell脚本关于条件分支的语句有if、case。

Table of Contents

if

和其他编程语言一样,shell程序的if语句,条件分支也分为单分支、双分支以及多分支。

# 单分支
if 条件 ;then
  ……
fi

# 双分支
if 条件 ;then
  ……
else
  ……
fi

# 多分支
if 条件;then
  ……
elif 条件;then
  ……
else
  ……
fi

首先,我们来用一个简单的例子来练练手,写一个shell脚本,该脚本功能是当用户输入一个得分时,程序通过得分来输出不同的评语,不及格、良好、优秀等。

首先,我们需要先提示用户,让用户输入一个三位数以内的数字。当用户输入的格式不正确的时候,需要告诉用户重新输入成绩,然后退出程序。代码如下:

read -p "请输入成绩,成绩范围0-100: " score

if [ -z `echo $score | egrep '^[0-9]+$'` ];then
    echo "输入的成绩格式不正确"
fi

上述代码,我们用到了if的单分支结构。接下来,我们需要用到多分支了,根据成绩打印出不同的评语。

if ((score >= 90));then
    echo '优秀'
elif ((score >= 80));then
    echo '良好'
elif ((score >= 70));then
    echo '一般'
elif ((score >= 60 ));then
    echo '及格'
else
    echo '不及格'
fi

上述代码非常的简单,下面我们贴出完整的代码,完整代码如下:

#!/bin/bash

read -p "请输入成绩,成绩范围0-100: " score

if [ -z `echo $score | egrep '^[0-9]+$'` ];then
    echo "输入的成绩格式不正确"
fi

if ((score >= 90));then
    echo '优秀'
elif ((score >= 80));then
    echo '良好'
elif ((score >= 70));then
    echo '一般'
elif ((score >= 60 ));then
    echo '及格'
else
    echo '不及格'
fi

case

下面,我们来看另一个条件分支语句case,它的基本结构如下:

case $变量 in 
    "内容1")
        代码块1
    ;;
    "内容2")
        代码块2
    ;;
    ……
    *)
        代码块n
    ;;
esac

上述的内容意思是这样的,当“变量值”等于“内容1”时,执行代码块1,等于“内容2”时,执行代码块2,如果前面的都不满足,则执行代码块n。

接下里,我们通过一个简单的案例来看看case是如何运用的。

#!/bin/bash
case $1 in
    "start")
        echo "this code is start"
    ;;

    "stop")
        echo  "this code is stop"
    ;;

    "restart")
        echo "this code is restart"
    ;;

    *)
        echo  "Usage 
#!/bin/bash
case $1 in
"start")
echo "this code is start"
;;
"stop")
echo  "this code is stop"
;;
"restart")
echo "this code is restart"
;;
*)
echo  "Usage ${0} {start|stop|restart}"
;;
esac
{start|stop|restart}" ;; esac

上述代码的含义是,当用户输入参数为start时,程序打印this code is start,当输入的参数为stop时,输出this code is stop,当输入参数为restart时,输出this code is restart,否则的话输入“Usage 脚本文件名 {start|stop|restart}”。