Shell条件测试 if 流程控制
文件测试
数值比较
字符串比较
1、shell条件测试
格式1:test 条件表达式
格式2:[ 条件表达式 ]
格式3:[[ 条件表达式 ]]
if后面可用跟任何命令
如果想让条件为真后什么也不输出,则使用:命令,:命令=true命令
1.1文件测试
格式:[ 操作符 文件或目录 ]
选项:
[ -e dir|file ] 测试目录|文件是否存在
[ -d dir ] 测试是否为目录
[ -f file ] 测试是否为文件
[ -r file ] 测试文件是否可读—当前用户
[ -x file ] 测试文件是否可执行—当前用户
[ -w file ] 测试文件是否可写—当前用户
[ -L file ] 测试文件是否为链接文件
#-------------模拟mysql备份------------ back_dir=/back/`date +%Y%m%d` if [ ! -d $back_dir ];then mkdir -p $back_dir fi echo "开始备份..."
1.2整数比较
格式:[ 整数1 操作符 整数2 ]
选项:
[ 1 -gt 10 ] 大于
[ 1 -lt 10 ] 小于
[ 1 -eq 10 ] 等于
[ 1 -ne 10 ] 不等于
[ 1 -ge 10 ] 大于等于
[ 1 -le 10 ] 小于等于
1.2.1创建用户
read -p "please input username: " user if id $user &>/dev/null;then echo "user $user already exists" exit else useradd $user if [ $? -eq 0 ];then echo "user is created..." echo "123"|passwd --stdin $user &>/dev/null if [ $? -eq 0 ];then echo "Initialize the password for '123'" fi fi fi
1.2.2磁盘空间告警
#!/bin/bash =======================第一种========================= disk_used=$(df -hT|grep '/$'|awk '{print $(NF-1)}'|awk -F "%" '{print $1}') mail_user=jiangxiaolong if [ $disk_used -ge 9 ];then echo "`date +%Y-%m-%d-%X` disk / used is : ${disk_used}%" | mail -s "disk waring..." $mail_user fi =======================第二种========================= disk_gen_used=$(df | grep '/$' | awk '{print $3}') disk_gen_total=$(df | grep '/$' | awk '{print $2}') disk_gen_percent=$(($disk_gen_used*100/$disk_gen_total)) disk_myscr_used=$(df | grep '/my_scripts' | awk '{print $3}') disk_myscr_total=$(df | grep '/my_scripts' | awk '{print $2}') disk_myscr_percent=$(($disk_myscr_used*100/$disk_myscr_total)) #disk_gen_content=`cat /tmp/disk_war.txt | grep -v "my_scripts"` #disk_myscr_content=`cat /tmp/disk_war.txt | grep "my_scripts"` gen_file=/tmp/disk_gen_war.txt myscr_file=/tmp/disk_myscr_war.txt rm -rf $genfile $myscr_file if [ $disk_gen_percent -ge 90 ];then echo "$(date +%F-%X) disk / is used: ${disk_gen_percent}%" > $gen_file if [ -f $gen_file ];then mail -s "disk / war.." jiangxiaolong < $gen_file fi rm -rf $gen_file fi if [ $disk_myscr_percent -ge 90 ];then echo "$(date +%F-%X) disk /my_scripts is used: ${disk_myscr_percent}%" > $myscr_file if [ -f $myscr_file ];then mail -s "disk /my_scripts war..." jiangxiaolong < $myscr_file fi rm -rf $myscr_file fi
1.2.3内存空间告警
#!/bin/bash mem_used=$(free -m | grep '^Mem' |awk '{print $(NF-4)}') mem_total=$(free -m | grep '^Mem' |awk '{print $(NF-5)}') mem_percent=$(($mem_used*100/$mem_total)) mem_gj_file=/tmp/memory.txt rm -rf $mem_gj_file if [ $mem_percent -ge 80 ];then echo "$(date +%F) memory is used: $mem_percent " > $mem_gj_file fi if [ -f $mem_gj_file ];then mail -s "memory war..." jiangxiaolong < $mem_gj_file rm -rf $mem_gj_file fi
1.3c语言风格的数值比较
((1<2));echo $? 小于 ((1==2));echo $? 等于 ((1>2));echo $? 大于 ((1>=2));echo $? 大于等于 ((1<=2));echo $? 小于等于 ((1!=2));echo $? 不等于 ((`id -u`)>0);echo $? 大于 (($UID==0));echo $? 等于
1.4字符串比较
建议变量名和变量值都使用双引号,否则当变量不存在时会报语法错误
变量为空或未定义,长度都为0
[ "$USER" = "root" ];echo $? [ "$USER" == "root" ];echo $? BBB="" echo ${#BBB} 0 [ -z "$BBB" ] -z用来测试字符长度是否为0 [ -n "$BBB" ] -n用来测试字符长度是否不为0
下面脚本中的一些解释
[[ ! "n u m " = [ 0 − 9 ] + num" =~ ^[0-9]+num"=
[
0−9]+ ]] 双方括号用来测试正则表达式,这是表达式表示只能以0-9开头结尾的数字可以有多个,^:开头 ,$:结尾 ,+可以有多个
[[ "c o n f i r m " = [ y ∣ Y ] confirm" =~ ^[y|Y]confirm"=
[
y∣Y] ]] [[ "c o n f i m " = [ c r e a t e ] confim" =~ ^[create]confim"=
[
create] ]] [[ "c o n f i m " = [ d e l e t e ] confim" =~ ^[delete]confim"=
[
delete] ]]
上述三个例子是字符判断也是正则表达式,这里采用正则是为了练习,更严谨的发放是使用字符判断,例如
[ “$confim” =“create” ]
包含其中1个字符的情况下建议使用正则,多个字符同时满足则建议使用字符串比较
如果函数较长可以写到单独的文件中,然后用source命令加载即可
2.if流程控制
2.1单分支if语句结构
if 命令序列
then
fi
2.1.按套路出牌的批量创建用户
#!/bin/bash read -p "please input number: " num read -p "please input prefix: " prefix for i in `seq 1 $num` do user=$prefix$i useradd -M $user echo "123"|passwd --stdin $user &>/dev/null if [ $? -eq 0 ];then echo "$user is created..." fi done --------------------------附赠:既然可以创建那么就可以删除------------------- read -p "please input number: " num read -p "please input prefix: " prefix for i in `seq 1 $num` do user=$prefix$i if [ -e /home/$user ];then userdel -r $user else userdel $user fi if [ $? -eq 0 ];then echo "$user is delete..." fi done
2.1.2不按套路出牌创建用户
#!/bin/bash -------------------创建的------------------ read -p "please input prefix: " prefix if [ -z "$prefix" ];then echo "error prefix" exit fi read -p "please input number: " num if [[ ! "$num" =~ ^[0-9]+$ ]];then echo "error num" exit fi read -p "Confirm to create user {prefix+num} [y/n|Y/N]:" confirm if [[ "$confirm" =~ ^[y|Y]$ ]];then echo "create user begin...." elif [[ "$confirm" =~ ^[n|N]$ ]];then echo "keep create user..." else echo "bye..." fi for i in `seq $num` do user=$prefix$i useradd -M $user echo "123"|passwd --stdin $user &>/dev/null if [ $? -eq 0 ];then echo "$user is created..." fi done -----------------------删除的----------------- read -p "please input prefix: " prefix if [ -z "$prefix" ];then echo "error prefix" fi read -p "please input number: " num if [[ ! "$num" =~ ^[0-9]+$ ]];then echo "error num" fi read -p "Confirm to delete user {prefix+num} [y/n|Y/N]:" confirm if [[ "$confirm" =~ ^[y|Y]$ ]];then echo "delete user begin...." elif [[ "$confirm" =~ ^[n|N]$ ]];then echo "keep delete user..." else echo "bye..." fi for i in `seq $num` do user=$prefix$i if [ -e /home/$user ];then userdel -r $user else userdel $user fi if [ $? -eq 0 ];then echo "$user is delete..." fi done
2.1.3按套路出牌升级版
加了函数,让用户选择是要创建用户还是删除用户
#!/bin/bash #-----------------批量创建用户,常规模式------------ #先将创建和删除的命令分别做成函数,在根据输入内容判断执行那个函数 usadd(){ read -p "please input prefix: " prefix read -p "please input number: " num for i in `seq 1 $num` do user=$prefix$i useradd -M $user echo "123"|passwd --stdin $user &>/dev/null if [ $? -eq 0 ];then echo "$user is created..." fi done } #--------------删用户 usdel(){ read -p "please input prefix: " prefix read -p "please input number: " num for i in `seq 1 $num` do user=$prefix$i if [ -e /home/$user ];then userdel -r $user else userdel $user fi if [ $? -eq 0 ];then echo "$user is delete..." fi done } read -p "create or delete [create|delete]: " confirm if [ "$confirm" = "create" ];then usadd elif [ "$confirm" = "delete" ];then usdel else echo "bye!!!!!" fi
2.1.4不按套路出牌升级版
加了函数自由选择
#!/bin/bash ################################################################ # 不按常规走,输入的不是合法的数字|前缀就退出 # # -----------------批量创建用户,常规模式------------ # # 根据用户输入的num和prefix,用户确认后将创建对应的用户 # # ################################################################ usadd(){ read -p "please input prefix: " prefix if [ -z "$prefix" ];then echo "error prefix" exit fi read -p "please input number: " num if [[ ! "$num" =~ ^[0-9]+$ ]];then echo "error num" exit fi read -p "Confirm to create user {prefix+num} [y/n|Y/N]:" confirm if [[ "$confirm" =~ ^[y|Y]$ ]];then echo "create user begin...." elif [[ "$confirm" =~ ^[n|N]$ ]];then echo "keep create user..." else echo "bye..." fi for i in `seq $num` do user=$prefix$i useradd -M $user echo "123"|passwd --stdin $user &>/dev/null if [ $? -eq 0 ];then echo "$user is created..." fi done exit } ################################################################ # # # --------------删用户----------------------- # # 根据用户输入的num和prefix,用户确认后将删除对应的用户 # ################################################################ usdel(){ read -p "please input prefix: " prefix if [ -z "$prefix" ];then echo "error prefix" fi read -p "please input number: " num if [[ ! "$num" =~ ^[0-9]+$ ]];then echo "error num" fi read -p "Confirm to delete user {prefix+num} [y/n|Y/N]:" confirm if [[ "$confirm" =~ ^[y|Y]$ ]];then echo "delete user begin...." elif [[ "$confirm" =~ ^[n|N]$ ]];then echo "keep delete user..." else echo "bye..." fi for i in `seq $num` do user=$prefix$i if [ -e /home/$user ];then userdel -r $user else userdel $user fi if [ $? -eq 0 ];then echo "$user is delete..." fi done exit } read -p "create or delete [create|delete]: " confirm if [ "$confirm" = "create" ];then usadd elif [ "$confirm" = "delete" ];then usdel else echo "bye!!!!!" fi
2.2.if双分支语句结构
if 命令序列;then
else
fi
2.3if多分支语句结构
if 条件测试1
then 命令序列
elif 条件测试2
then 命令序列
elif 条件测试3
then 命令序列
else 命令序列
fi
2.3.1安装httpd
#!/bin/bash www=www.baidu.com ping -c1 $www &>/dev/null if [ $? -eq 0 ];then echo "check soft..." yum list installed | grep http &>/dev/null if [ ! $? -eq 0 ];then echo "begin install httpd..." yum -y install httpd else echo "httpd is installed..." fi systemctl restart httpd systemctl enable httpd firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload elif ping -c 192.168.81.1 &>/dev/null;then echo "check dns..." else echo "check ipaddress..." fi systemctl status httpd &>/dev/null if [ $? -eq 0 ];then http_port=$(netstat -lnpt | grep http | awk '{print $4}' |awk -F':' '{print $4}') http_address=$(netstat -lnpt | grep http | awk '{print $4}' |awk -F'80' '{print $1}') http_pid=$(netstat -lnpt | grep http | awk '{print $(NF)}' | awk -F"/" '{print $1}') echo "http is up..." echo "http port is: $http_port" echo "http listen address is: $http_address" echo "http pid is: $http_pid" fi
2.3.2配置yum源文件
#!/bin/bash os_version=$(cat /etc/redhat-release | awk '{print $(NF-1)}'|awk -F"." '{print $1"."$2}') [ ! -e /etc/yum.repos.d/bak/$(date +%F-X) ] || mkdir -p /etc/yum.repos.d/bak/$(date +%F-X) mv /etc/yum.repos.d/* /etc/yum.repos.d/bak &>/dev/null if [ $os_version = "7.6" ];then cat >/etc/yum.repos.d/centos7u6.repo <<-EOF [centos7u6] name=centos7u6 baseurl=file:///media enabled=1 gpgcheck=0 EOF echo "centos $os_version yumconfig finish..." elif [ $os_version = "6.5" ];then wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo elif [ $os_version = "5.4" ];then wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo else echo "error osversion" fi