您的位置:首页 > 运维架构 > Shell

UNIX/Linux shell脚本 if语句的几个案例(适合Linux初学者)

2012-12-05 12:57 811 查看




小诺技术博客新地址: www.rsyslog.org ,欢迎前来访问!

if语法:

1、单分支的if语句

if 条件测试命令

then

命令序列

fi

2、双分支的if语句

if 条件测试命令

then

命令序列1

else

命令序列2

fi

3、多分支的if语句(elif 可以嵌套多个,一般多了用case表达)

if 条件测试命令1

then

命令序列1

elif 条件测试命令2

then

命令序列2

.........

else

命令序列n

fi

案例1

#!/bin/bash

#######################################################################

# "提示用户指定备份目录的路径,若目录存在则显示信息跳过,否则显示相应提示信息,并创建该目录"

# "-----Designed by UNIX.ROOT Email: UNIX.ROOT@hotmail.com"

######################################################################

read -p "What is your backup directoy:" BakDir

if [ -d $BakDir ]; then

echo "$BakDir already exist."

else

echo "$BakDir is not exist, will make it."

mkdir $BakDir

fi





本文出自 “UNIX/Linux Discovery” 博客,请务必保留此出处http://dreamfire.blog.51cto.com/418026/1079173

案例2

#!/bin/bash

#######################################################################

#统计当前登录到系统中的用户数量,若判断是否超过三个,若是则显示实际数量并给出警告信息,否则列出

登录的用户账户名称及所在终端

# "-----Designed by UNIX.ROOT Email: UNIX.ROOT@hotmail.com"

######################################################################

UserNum=`who | wc -l`

if [ $UserNum -gt 3 ]; then

echo "Alert, too many login users ( Total: $UserNum)."

else

echo "Login Users:"

who | awk `{print $1,$2}`

fi





本文出自 “UNIX/Linux Discovery” 博客,请务必保留此出处http://dreamfire.blog.51cto.com/418026/1079173

诺技术博客新地址: www.rsyslog.org ,欢迎前来访问!

案例3

#!/bin/bash

#######################################################################

#每隔5分钟检测一次 mysql服务进程的运行状态,若发现mysql进程已经终止,则在"/var/log/messages"文件中追加写入日志信息(包括当时时间)并重启httpd服务;否则不做任何操作

# -----Designed by UNIX.ROOT Email: UNIX.ROOT@hotmail.com

######################################################################

service httpd status &> /dev/null

if [ $? -ne 0 ] ; then

echo "At time:$(date):Http Server is down." >> /var/log/messages

/etc/rc.d/init.d/httpd start

fi

# crontab -e

#*/5 * * * * /data/shell.sh/chkdhcpd.sh





本文出自 “UNIX/Linux Discovery” 博客,请务必保留此出处http://dreamfire.blog.51cto.com/418026/1079173

案例4

#!/bin/bash

#######################################################################

# 检查portmap进程是否已经存在,若已经存在则输出 "Portmap service is running.";否则检查是否存在"/etc/rc.d/init.d/portmap"可执行脚本,存在则启动portmap服务,否则提示"no portmap script files"

# -----Designed by UNIX.ROOT Email: UNIX.ROOT@hotmail.com

######################################################################

pgrep portmap &> /dev/null

if [ $? -eq 0 ] ; then

echo "Protmap service is running."

elif [ -x "/etc/rc.d/init.d/portmap" ]; then

/etc/rc.d/init.d/portmap start

else

echo "no portmap script files."

fi





诺技术博客新地址: www.rsyslog.org ,欢迎前来访问!

本文出自 “UNIX/Linux Discovery” 博客,请务必保留此出处http://dreamfire.blog.51cto.com/418026/1079173
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息