shell的流程控制一般包括if、for、while、case/esac、until、break、continue语句构成。
if语句开发
单分支if
//方式1
if <条件表达式>
then
代码。。。
fi
//方式2
if <条件表达式>;then
代码。。。
fi
双分支if
if <条件表达式>
then
代码1
if <条件表达式>
then
代码2
fi
fi
if-else处理
if <条件表达式>
then
当条件成立,会执行我
else
否则就会执行我
fi
// if-else 多分支处理
if <条件表达式1>
then
代码1
elif <条件表达式2>
then
代码2
elif <条件表达式3>
then
代码3
else
代码4
fi
if 实战
将之前的[] [[]] test条件判断的语句改成if+条件判断的语句
xiao123@xiao123:~/Downloads/shscripts$ [ -f /etc/hosts ] && echo yes
yes
xiao123@xiao123:~/Downloads/shscripts$ [[ -f /etc/hosts ]] && echo yes
yes
xiao123@xiao123:~/Downloads/shscripts$ test -f /etc/hosts && echo yes
yes
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_1.sh
[] is ok
[[]] is ok
test is ok
xiao123@xiao123:~/Downloads/shscripts$ cat ./if_1.sh
#! /bin/bash
if [ -f /etc/hosts ]
then
echo "[] is ok"
fi
if [[ -f /etc/hosts ]]; then
echo "[[]] is ok"
fi
if test -f /etc/hosts; then
echo "test is ok"
fi
xiao123@xiao123:~/Downloads/shscripts$
开发系统监控脚本
开发shell脚本
- 检查Linux剩余可用内存,当可用内存小于100M,就发邮件给运维。
- 并且该脚本加入crontab,每3分钟检查一次内存。
xiao123@xiao123:~/Downloads/shscripts$ bash free_1.sh
Current memory is 1081
内存不足,抓紧维护服务器!
xiao123@xiao123:~/Downloads/shscripts$ cat free_1.sh
#! /bin/bash
FreeMem=`free -m |awk 'NR==2 { print $NF }'`
CHARS="Current memory is ${FreeMem}"
if [ "${FreeMem}" -lt 2100 ];
then
echo ${CHARS}|tee /tmp/message.txt
# mail -s "主题" 收件人 <
# mail -s "`date +%F-%T` ${CHARS}" yc_urrr@163.com < /tmp/message.txt
echo "内存不足,抓紧维护服务器!"
fi
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ crontab -e
crontab: installing new crontab
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ crontab -l
*/3 * * * * /bin/bash /home/xiao123/Downloads/shscripts/free_1.sh
xiao123@xiao123:~/Downloads/shscripts$
if实战开发
单分支实战
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 1 2
yes, 1 less than 2
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 2 2
yes, 2 equal 2
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 3 2
yes, 3 greather than 2
xiao123@xiao123:~/Downloads/shscripts$ cat ./if_read.sh
#! /bin/bash
a=$1
b=$2
if [ $a -lt $b ]; then
echo "yes, $a less than $b"
fi
if [ $a -eq $b ]; then
echo "yes, $a equal $b"
fi
if [ $a -gt $b ]; then
echo "yes, $a greather than $b"
fi
xiao123@xiao123:~/Downloads/shscripts$
多分支实战
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 1 1
yes, 1 equal 1
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 1 2
yes, 1 less than 2
xiao123@xiao123:~/Downloads/shscripts$ bash ./if_read.sh 2 1
yes, 2 greather than 1
xiao123@xiao123:~/Downloads/shscripts$ cat ./if_read.sh
#! /bin/bash
a=$1
b=$2
if [ $a -lt $b ]; then
echo "yes, $a less than $b"
elif [ $a -eq $b ]; then
echo "yes, $a equal $b"
elif [ $a -gt $b ]; then
echo "yes, $a greather than $b"
fi
xiao123@xiao123:~/Downloads/shscripts$