Shell编程及自动化运维流程控制:if

Posted 资本家的鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Shell编程及自动化运维流程控制:if相关的知识,希望对你有一定的参考价值。

单分支结构

语法

if [ command/test ];then
符合该条件执行的语句
fi

示例

由用户输入用户名,如果用户不存在,则创建该用户

#!/bin/bash
read -p "Input username: " name
id $name &> /dev/null
if [ $? -ne 0 ]; then
useradd $name
fi


双分支结构

语法

if 条件测试
then
命令序列
else
命令序列
fi

示例

用户输入用户名, 如果用户不存在,则创建该用户,并设置密码为123456;否则,提示用户已经存在

#!/bin/bash
read -p "Input username: " name

#id $name &> /dev/null
#if [ $? -eq 0 ];then

if id $name &> /dev/null; then
echo "$name already exist"
else
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"
fi


多分支结构

语法

多分支结构
if 条件测试1
then 命令序列

elif 条件测试2
then 命令序列

elif 条件测试3
then 命令序列...

else 命令序列
fi

示例

取出系统时间的小时,对数字进行判断  

  • 6--10  this is morning
  • 11-13  this is noon
  • 14-18  this is afternoon
  • 其他   this is night
#!/bin/bash
hour=`date +%H`
if [ $hour -ge 6 -a $hour -le 10 ];then
echo "This is morning"
elif [ $hour -ge 11 -a $hour -le 13 ];then
echo "This is noon"
elif [ $hour -ge 14 -a $hour -le 18 ];then
echo "This is afternoon"
else
echo "This is night"
fi


嵌套结构

语法

if 条件测试1  then 命令序列
if 条件测试1 then 命令序列

else 命令序列
fi

else 命令序列
fi

示例Shell编程及自动化运维(7)流程控制:if_if

read -p "Input username: " name
id $name &> /dev/null

if [ $? -eq 0 ];then
echo "$name 存在"

else
useradd $name
echo "$name create finished"
read -p "请输入用户密码: " pass
if [ $#pass -ge 7 ];then
echo "$pass" | passwd --stdin $name
echo "$name 用户密码是 $pass"
else
echo "密码不合格"
fi

fi

调试脚本

  • sh -n 02.sh 仅调试脚本中的语法错误。
  • sh -vx 02.sh 以调试的方式执行,查询整个执行过程


练习

#!/usr/bin/bash
DUG=`df -hT |grep /$|awk print $6|sed s/%//`
CUG=`mpstat|grep all|awk print $11|awk -F. print $1`
used=`free|grep Mem|awk print $3`
total=`free|grep Mem|awk print $2`
MUG=$(expr $used / $total)
d=`expr 100 - $CUG`
if [ $DUG -ge 90 ];then
echo "当前磁盘占用超过80%"
fi
if [ $d -ge 80 ];then
echo "当前CPU使用率以达到80%"
fi
if [ $MUG -ge 90 ];then
echo "当前内存占用率已达到90%"
fi


以上是关于Shell编程及自动化运维流程控制:if的主要内容,如果未能解决你的问题,请参考以下文章

运维自动化

shell 编程进阶与自动化脚本expect的运用

Shell编程Shell中的流程控制之if语句

Puppet---自动化运维工具(进阶)

Shell编程及自动化运维位置变量

Shell编程及自动化运维预定义变量