4.3.1 if条件测试语句

if语句分为单分支结构、双分支结构、多分支结构

(1)使用单分支的if条件语句来判断/media/cdrom目录是否存在,若不存在就创建这个目录,反之则结束条件判断和整个shell脚本的执行

# vim mkcdrom.sh
#!/bin/bash
DIR=/media/cdrom
if [ ! -e $DIR ]
        then 
                mkdir /media/cdrom
        fi

使用“bash 脚本名称”的方式来执行脚本,并使用ls -ld命令来查看/media/cdrom 目录是否已经成功创建

# bash mkcdrom.sh
# ls -ld /media/cdrom/
dr-xr-xr-x. 7 root root 2048 Apr 21  2022 /media/cdrom/

(2)使用双分支的if条件语句来验证某台主机是否在线

# vim chkhost.sh 
#!/bin/bash
ping -c 3 -i 0.2 -w 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
        echo "This Host is On-line."
else
        echo "This Host is Off-line."
fi

执行脚本

# bash chkhost.sh  192.168.20.2

(3)使用多分支来判断用户输入的分数在哪个区间内

# vim chkscore.sh
#!/bin/bash
read -p "Enter your score:" score
if [ $score -ge 85 ] && [ $score -le 100 ];
then
        echo "your Score is Excellent."
        elif [ $score -ge 75 ] && [ $score -le 84 ];
        then
                echo "your score is pass."
        else
                echo "your score fail"
        fi

执行脚本

# bash chkscore.sh 
Enter your score:85
your Score is Excellent

最后更新于

这有帮助吗?