一:if语句结构
(1)单分子if语句
if 条件测试命令
then
命令序列
fi
(2)双方支if语句
if 条件测试命令
then
命令序列1
else
命令序列2
fi
(3)多分支if语句
if 条件测试命令1
then
命令序列1
elif 条件测试命令2
then
命令序列2
then
else
命令序列3
fi
案例(一)
检查"/var/log/messages" 文件是否存在,存在则统计文件内容的行数并输出,否则不做任何操作(合理使用变量,可以提高编程
效率)。
vim test1.sh
#! /bin/bash
logfile="/var/log/messages"
if [ -f $logfile ]; then
wc -lwc $logfile
fi
案例(二)
提示用户指定备份目录的路径,目录已存在则提示跳过信息,否则显示相应信息创建该目录。
vim test2.sh
#! /bin/bash
read -p "What is your backup directory:" bakdir
if [ -d $bakdir ]; then
echo "$bakdir already exist."
else
echo "$bakdir is not exist, will make it."
mkdir $bakdir
fi
案例(三)
统计当前登录到系统用户数,并判断是否超过三个,超过三个用户提示信息并提示警告信息,如果没有超过三个并列出登录用户账号
名称以及所在终端。
vim test3.sh
#! /bin/bash
benet=`who | wc -l`
if [ $benet -gt 3 ] ; then
echo "Alert, too many login users ( Total: $benet )."
else
echo "Login user:"
who | awk '{print $1,$2}'
fi
案例(四)
检查portmap进程是否存在,如存在输出“portmap service isrunning。”否则检查是否存在“/etc/rc.d/init.d/portmap”可执
行脚本,存在则启动portmap服务,否则提示“no portmap script file.”
vim test4.sh
#! /bin/bash
pgrep portmap &> /dev/null
if [ $? -eq 0 ]; then
echo "portmap service is running."
elif [ -x "/etc/rc.d/init.d/portmap" ]; then
service portmap start
else
echo "no portmap script file."
fi
案例(五)
每隔五分钟检测一次msyql服务进程的运行状态,发现mysqld进程已终止,则在“/var/log/messages”文件中追加日志信息(包括
当时时间),并重启mysqld服务;负责不进行任何操作。
vim test5.sh
#! /bin/bash
service mysqld status &> /dev/null
if [ $? -eq 0 ]; then
echo "At time: `date` : MYSQL Server is down." >> /var/log/messages
service mysqld restart
fi
本文出自 “dsafsa_技术博客” 博客,谢绝转载!