Shell programming flow control-if

Process control

Shell programming statements are executed sequentially, in order to achieve different results, you need to change the order of execution

Process control-if

Single branch if conditional statement

if [ 条件判断 ] ;then
    执行语句
fi
#隐含:如果条件判断不成立,就不执行下面的语句

例题:根分区大于80%就打印告警信息

#!/bin/bash
a=$(df -h | grep /dev/sda5  | awk '{print $5}' | cut -d % -f 1)
if [ $a -gt 80 ] ;then
  echo "Warning: Disk alert"
fi

Double branch if conditional statement

if [ 条件判断 ] ;then
    条件成立执行语句
  else
    条件不成立执行语句
fi

例子:监控nginx服务是否down掉,如果down掉就通知管理员并且启动服务
#!/bin/bash
a=$(ps -ef | grep nginx | grep "master process")
    
if [ -n "$a" ];then 
     echo "OK"
   else
     echo "nginx Alarm" ; systemctl restart nginx
fi

Multi-branch if conditional statement

if [ 条件判断 ] ;then
    条件成立执行语句
  elif
    条件成立执行语句
  elif
    条件成立执行语句
  elif
    条件成立执行语句
  else
    条件不成立执行语句
fi
#elif或的关系,只要符合其中一个就执行,第一个如果匹配到后续的elif不会再匹配

例子:判断一个文件是否是普通文件还是目录
#!/bin/bash

read -t 30 -p "Please enter the file path:" file
if [ -f $file ];then
  echo "The $file is common file" 
elif [ -d $file ];then
  echo "The $file is directory"
else 
  echo "The $file is unknown"
fi
#注意【】需要2边空格

Guess you like

Origin blog.csdn.net/yangshihuz/article/details/111476518