练习19:写一个脚本:可以接受一个参数,其使用形式如下:
script.sh {start|stop|restart|status}
如果参数为start,创建空文件/var/lock/subsys/script,并显示“Starting script successfully.”;
如果参数为stop,则删除文件/var/lock/subsys/script,并显示“Stop script finished.”;
如果参数为restart,则删除文件/var/lock/subsys/script后重新创建,并显示“Restarting script successfully.”;
如果参数为status,那么:
如果/var/lock/subsys/script文件存在,则显示为“script is running.”
否则,则显示为“script is stopped.”
其它任何参数:则显示“script.sh {start|stop|restart|status}”
#!/bin/bash # Date: 2015-04-06 # Author: ArvinLau # Description: # Version: 1.0 FileName=`basename $0` FilePath="/var/lock/subsys/$FileName" #变量替换,使用双引号 if [ $# -lt 1 ]; then echo "Usage:$0 {start | restart | stop | status}" exit 5 fi if [ $1 == start ]; then touch $FilePath echo "Starting $FileName successfully." elif [ $1 == stop ]; then rm -f $FilePath echo "Stop script finished." elif [ $1 == restart ]; then rm -f $FilePath touch $FilePath echo "Restarting script successfully." elif [ $1 == status ]; then if [ -e $FilePath ]; then echo "Script is running." elif [ ! -e $FilePath ]; then echo "Script is stopped." fi else echo "Usage:$0 {start | restart | stop | status}" exit 7 fi
#虽然目前知识所写的脚本,功能简单,但可以尽可能的针对实际情况进行完善,下面这个脚本,就文件是否存在进行判断,补充脚本的不足。
#!/bin/bash # Date: 2015-04-06 # Author: ArvinLau # Description: # Version: 1.0 FileName=`basename $0` FilePath="/var/lock/subsys/$FileName" #变量替换,使用双引号 if [ $# -lt 1 ]; then echo "Usage:$0 {start | restart | stop | status}" exit 5 fi if [ $1 == start ]; then if [ -e $FilePath ]; then #判断文件是否存在 echo "$FilePath is running." else touch $FilePath echo "Starting $FileName successfully." fi elif [ $1 == stop ]; then if [ -e $FilePath ]; then #判断文件是否存在 rm -f $FilePath echo "Stop script finished." else echo "$FilePath is stopped." fi elif [ $1 == restart ]; then if [ ! -e $FilePath ]; then #如果文件不存在 echo "$FilePath is stopped." else rm -f $FilePath touch $FilePath echo "Restarting script successfully." fi elif [ $1 == status ]; then if [ -e $FilePath ]; then echo "Script is running." elif [ ! -e $FilePath ]; then echo "Script is stopped." fi else echo "Usage:$0 {start | restart | stop | status}" exit 7 fi
以上的脚本就是sysv风格的服务脚本
Redhat系列可以用以下方式执行这些服务脚本
# service network start
# /etc/rc.d/init.d/network start
# /etc/init.d/network start
本文出自 “Arvin Lau” 博客,请务必保留此出处http://64314491.blog.51cto.com/2784219/1629219
原文地址:http://64314491.blog.51cto.com/2784219/1629219