六、Shell脚本高级编程实战第六部
一、写一个start_nginx脚本,当启动、停止、重启时利用系统函数模拟实现系统脚本启动的特殊颜色效果 (用if实现)
#!/bin/sh
. /etc/init.d/functions
. /etc/init.d/functions
if [ $# -ne 1 ]
then
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
then
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
if [ "$1" == "start" ]
then
action "start nginx" /bin/true
elif [ "$1" == "stop" ]
then
action "stop nginx" /bin/true
elif [ "$1" == "restart" ]
then
action "restart nginx" /bin/true
else
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
then
action "start nginx" /bin/true
elif [ "$1" == "stop" ]
then
action "stop nginx" /bin/true
elif [ "$1" == "restart" ]
then
action "restart nginx" /bin/true
else
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
结果测试:
二、什么是函数
简单的说,就是把程序里多次调用的部分定义成一份,然后起个名字,对于所有的调用,用这个名字就可以了。
优势:减少程序代码量;增加程序的可读、易读性;实现程序功能的模块化
三、用 if 和函数 实现 mysql的启动脚本
单实例:
1.启动服务: /application/mysql/bin/mysqld_safe &
2.停止服务: /application/mysql/bin/mysqladmin -uroot -poldboy124 shutdown
3.开发脚本代码:
#!/bin/sh
. /etc/init.d/functions
path="/application/mysql/bin"
user=root
pass=oldboy124
function usage(){
echo "$0 (start|stop|restart)"
exit 1
}
. /etc/init.d/functions
path="/application/mysql/bin"
user=root
pass=oldboy124
function usage(){
echo "$0 (start|stop|restart)"
exit 1
}
[ $# -ne 1 ] && usage
function start_mysql(){
cd /application/mysql && $path/mysqld_safe >/dev/null 2>&1 &
if [ $? -eq 0 ]
then
action "start mysql " /bin/true
else
action "start mysql" /bin/false
fi
}
cd /application/mysql && $path/mysqld_safe >/dev/null 2>&1 &
if [ $? -eq 0 ]
then
action "start mysql " /bin/true
else
action "start mysql" /bin/false
fi
}
function stop_mysql(){
$path/mysqladmin -u$user -p$pass shutdown >/dev/null 2>&1
if [ $? -eq 0 ]
then
action "stop mysql" /bin/true
else
action "stop mysql" /bin/false
fi
}
$path/mysqladmin -u$user -p$pass shutdown >/dev/null 2>&1
if [ $? -eq 0 ]
then
action "stop mysql" /bin/true
else
action "stop mysql" /bin/false
fi
}
if [ "$1" == "start" ]
then
start_mysql
elif [ "$1" == "stop" ]
then
stop_mysql
elif [ "$1" == "restart" ]
then
stop_mysql
start_mysql
else
usage
fi
stop_mysql
start_mysql
else
usage
fi
测试:
四、如何将一个脚本设置成开机自启动
例如:将上述脚本设置成开机自启动
首先,chkconfig命令可以设置开机自启动,但是启动命令必须在/etc/init.d里面,因为开机自启动会首先加载这里面的服务,当我们启动一个运行级别下的服务的时候,会通过chkconfig进行服务的管理,系统根据管理进行服务的优先级启动,所有如下草图:
1)在脚本中加入启动和关闭的优先顺序:如下图中的
2)将脚本交给chkconfig管理器
chkconfig --add mysqld
3)进行服务的开启:
chkconfig mysqld on