Linux学习日记 —— 11.5.1 Shell编程-流程控制-if语句

1. 单分支if条件语句
单分支if条件语句有三种写法:

if [ 条件判断式 ]; then
程序
fi

或者

if [ 条件判断式 ]
  then
   程序
fi

或者

if [ 条件判断式 ];then 操作;fi

说明:只有条件成立,才执行相应的操作。

示例:
if [ aa==aa ];then echo yes;fi

注意要点:

  • if语句使用fi结尾。
  • [ 条件 ] 中括号的内部两侧必须有空格。
  • 如果then和上面的if判断在同一行,要用分号;分割。
示例:判断根分区的使用率
写一个shell脚本usage.sh:
#!/bin/bash# 判断根分区的使用率
# Author: root
rate=$(df -h | grep "/dev/sda3" | awk '{print $5}' | cut -d "%" -f1)
# 把根分区/dev/sda3的使用率作为值赋予变量rate
if [ $rate -ge 80 ];then
echo "Warning! /dev/sda3 is full"
fi

2. 双分支if条件语句

基本格式:
if [ 条件 ]
  then
    条件成立时,执行操作1
  else
条件不成立时,执行操作2
fi
示例:备份mysql数据库
#!/bin/bash
#备份mysql数据库
#Author: root
ntpdate asia.pool.ntp.org &>/dev/null
#同步系统时间,并将执行结果直接丢弃(即不输出到屏幕)
#Linux默认没有ntpdate命令,可用 yum -y install ntpdate 安装

date=$(date +%y%m%d)
#把当前系统时间按照“年月日”格式赋予变量date

size=$(du -sh /var/lib/mysql)
#统计mysql数据库的大小,并把其赋予size变量

if [ -d /tmp/dbbak ]
 then
    echo "Date: $date" > /tmp/dbbak/dbinfo.txt
    echo "Data size: $size" >> /tmp/dbbak/dbinfo.txt
    cd /tmp/dbbak
    tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
    rm -rf /tmp/dbbak/dbinfo.txt
 else
    mkdir /tmp/dbbak
    echo "Date: $date" > /tmp/dbbak/dbinfo.txt
    echo "Data size: $size" >> /tmp/dbbak/dbinfo.txt
    cd /tmp/dbbak
    tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
    rm -rf /tmp/dbbak/dbinfo.txtfi

3. 多分支if条件语句

基本格式:
if [ 条件1 ]
    then
        当条件1成立时,执行操作1
elif [ 条件2 ]    
    then
        当条件2成立时,执行操作2...
else
    当所有条件都不成立时,执行最终操作
fi
示例:判断用户的输入
#!/bin/bash
#判断用户的输入
#Author:root
read -p "Please input a filename: " file
#接收键盘的输入,并赋给变量file
if [ -z $file ]
#判断file变量是否为空
 then
    echo "Error, please input a filename"
exit 1
#exit后面跟数字,可以指定脚本执行后 $? 的值。后面的代码不会执行。
elif [ ! -e $file ]
#判断file的值是否存在
 then 
    echo "Your input is not a  file"
exit 2
elif [ -f $file ]
#判断file的值是否为普通文件
 then
echo "$filename is a regular file"
elif [ -d $file ]
#判断file的值是否为目录文件
 then 
    echo "$file is a directory"
    else
echo "$file is a special file"
fi
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

烟敛寒林o

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

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

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

打赏作者

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

抵扣说明:

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

余额充值