shell编程之判断

1.if判断结构
if是最简单的判断语句,可以针对测试结果做相应处理。格式如下:

if expression ; then
   command
fi

如果expression测试返回为真,则执行command。如果执行的命令不止一条,则不同命令间用换行符隔开,如下所示:

if expression ; then
   command1
   command2
fi

例如:判断成绩

[root@node1 ~]# cat score.sh 
#!/bin/bash
echo -n "please input a score:"
read SCORE
if [ "$SCORE" -lt 60 ]; then
       echo "C"
fi
if [ "$SCORE" -lt 80 -a "$SCORE" -ge 60 ]; then
       echo "B"
fi
if [ "$SCORE" -ge 80 ]; then
       echo "A"
fi
[root@node1 ~]# sh score.sh 
please input a score:85
A

2.if/else判断结构
if/else语句可以完成两个分支的选择,如果if后的判断成立,则执行then之后的内容;否则执行else后的内容。

if expression ; then
   command
else 
   command
fi

例如:

[root@node1 ~]# cat check_file.sh 
#!/bin/bash
FILE=/var/log/messages
#FILE=/var/log/message1

if [ -e $FILE ]; then
    echo "$FILE exists"
else
    echo "$FILE not exists"
fi
[root@node1 ~]# sh check_file.sh 
/var/log/messages exists
[root@node1 ~]# vi check_file.sh 
[root@node1 ~]# cat check_file.sh 
#!/bin/bash
#FILE=/var/log/messages
FILE=/var/log/message1

if [ -e $FILE ]; then
    echo "$FILE exists"
else
    echo "$FILE not exists"
fi
[root@node1 ~]# sh check_file.sh 
/var/log/message1 not exists

3.if/elif/else判断结构
if语法的多层嵌套:

if expression1 ; then
   command1
else 
    if expression2; then
        command2
    else
        command3
    fi
fi

例如:

[root@node1 ~]# cat score.sh 
#!/bin/bash
echo -n "please input a score:"
read SCORE
if [ "$SCORE" -lt 60 ]; then
       echo "C"
else
    if [ "$SCORE" -lt 80 -a "$SCORE" -ge 60 ]; then
       echo "B"
    else
        if [ "$SCORE" -ge 80 ]; then
              echo "A"
        fi
    fi
fi
[root@node1 ~]# sh score.sh 
please input a score:78
B

4.case判断结构
case判断结构也可以用于多种可能情况下的分支选择。语法结构如下:

case VAR in
 var1)  command1 ;;
 var2)  command2 ;;
 var3)  command3 ;;
  ....
  *)  command ;;
  esac

例如:

[root@node1 ~]# cat os_type.sh 
#!/bin/bash
OS='uname -s'
case "$OS" in
FreeBSD) echo "this is FreeBSD" ;;
Linux ) echo "this is LINUX" ;;
*) echo "Failed to identify this OS" ;;
esac
[root@node1 ~]# sh os_type.sh 
Failed to identify this OS
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值