Shell中的流程控制语句
1、if语句
(1)单分支if条n件语句:
1)语法:
if [ 条件判断式 ];then
动作
fi
或:
if [ 条件判断式 ]
then
动作
fi
2)案例:
例1:判断文件是否存在,不存在则创建
#!/bin/sh
path=/root/script/
file=if1.sh
#mkdir
if [ ! -d ${path} ];then
mkdir -p ${path}
echo "${path} dir is not exit,already created it"
fi
#touch file
if [ ! -f ${path}${file} ]
then
touch ${path}${file}
echo "${path}${file} is not exit,already created it"
exit
fi
ls -l ${path}${file}
例2:判断磁盘使用率最大的分区,大于80%则报警
#!/bin/sh
usate=`df -h | tr -s " " | sort -nr -t" " -k5 | head -1 | awk '{print $5}' | cut -d"%" -f1`
namedev=`df -h | tr -s " " | sort -nr -t" " -k5 | head -1 | awk '{print $1}'`
if [ $usate -ge 80 ];then
echo "warning! ${namedev} is full"
fi
例3:新建shell脚本时写入注释信息并进入到第六行
#!/bin/bash
NEWNAME=$1
if ! grep -q "#!" ${NEWNAME} ;then
cat>>${NEWNAME}<<EOF
#!/bin/bash
#
#Author:Nan Li
#Date:`date +%F`
#Version:3.2
#Description:
EOF
fi
vim +6 ${NEWNAME}
(2)双分支if条件语句:
1)语法:
if [ 条件判断式 ]
then
条件成立时,执行该动作
else
条件不成立时,执行
fi
2)案例
例1:备份/etc目录
#!/bin/sh
rate=$(date +%F)
size=$(du -sh /etc)
if [ -d /tmp/etcbak ]
then
echo "Date:${rate}" >> /tmp/etcbak/etcinfo.txt
echo "Date size:${size}" >> /tmp/etcbak/etcifo.txt
cd /tmp/etcbak
tar -zcf etc-${rate}.tar.gz /etc etcinfo.txt &>/dev/null
rm -rf /tmp/etcbak/etcifo.txt
else
mkdir /tmp/etcbak
echo "Date:${rate}" >> /tmp/etcbak/etcinfo.txt
echo "Date size:${size}" >> /tmp/etcbak/etcifo.txt
cd /tmp/etcbak
tar -zcf etc-${rate}.tar.gz /etc etcinfo.txt &>/dev/null
rm -rf /tmp/etcbak/etcifo.txt
fi
例2:(方法1)判断httpd服务是否启动
#!/bin/sh
port=`nmap -sT 172.16.250.102 | grep tcp | grep http | awk '{print $2}'`
if [ "$port" == "open" ]
then
echo "$(date +%F-%T) httpd is ok" >> /tmp/autostart-acc.log
else
systemctl start httpd &> /dev.null
echo "$(date +%F-%T) restart httpd!!" >>/tmp/autostart-err.log
fi
(方法2)判断httpd服务是否启动
#!/bin/bash
while true; do
COUNT=`ps aux | grep "httpd" | grep -v "grep" | wc -l`
#echo ${COUNT}
if [ ${COUNT} -eq 0 ];then
systemctl start httpd
echo "------`date "+%F %T"` server down" >> httpd.log
fi
sleep 60
done
(2)双分支if条件语句:
1)语法:
if [ 条件判断式1 ]
then
条件1成立时,执行该动作
elif [ 条件判断式2 ]
then
条件2成立时,执行该动作
elif [ 条件判断式3 ]
then
条件3成立时,执行该动作
……
else
当所有条件都不成立时,执行该动作
fi
2)案例
例1:判断两个整数的大小
#!/bin/sh
read -p "please input two number:" a b
#no1
[ -z $a ] || [ -z $b ] && {
echo "please input two number agcogin"