Shell编程 之 if语句
1. 建立编程思想:(熟能生巧)
抄写程序 => 补全注释 => 删除注释 => 重写注释 => 删掉代码 => 重写代码 => 全部重写
2. 单分支 if 语句
2.1 基本结构

2.2 注意点

2.3 案例:
2.3.1 判断登陆的用户是否是 root 用户
#!/bin/bash
test=$(env |grep USER | cut -d "=" -f 2)
if [ "$test" == "root" ]
then
echo "current user is root"
fi
~
~
~
"if1.sh" 8L, 119C
2.3.2 判断分区使用率
#!/bin/bash
test=$(df -h | grep sda5 | awk '{print $5}' | cut -d "%" -f 1)
if [ "$test" -lt "90" ]
then
echo "/ usage is less than 90%"
fi
~
~
~
"if2.sh" 8L, 144C
3. 双分支 if 语句
3.1 基本结构

3.2 案例
3.2.1 判断输入的是否是一个目录
#!/bin/bash
read -t 30 -p "input a directory: " dir
if [ -d "$dir" ]
then
echo "$dir is a directory"
else
echo "$dir is not a directory"
fi
~
~
~
"if3.sh" 10L, 149C
3.3.2 判断Apache服务是否运行(有趣:脚本名含有httpd时,该脚本失效)
#!/bin/bash
test=$(ps aux | grep httpd | grep -v grep)
if [ -n "$test" ]
then
echo "httpd is OK" >> /tmp/autostart-acc.log
else
/etc/rc.d/init.d/httpd start &> /dev/null
echo "$(date) restart httpd!!" >> /tmp/autostart-err.log
fi
~
~
~
"if4.sh" 11L, 240C
posted on 2017-02-11 18:43 你的踏板车要滑向哪里 阅读(99) 评论(0) 收藏 举报
浙公网安备 33010602011771号