企业Shell面试题10:开发企业级MySQL启动脚本
说明:
MySQL启动命令为:
1 | /bin/sh mysqld_safe --pid- file =$mysqld_pid_file_path 2>&1 > /dev/null & |
停止命令逻辑脚本为:
1 2 3 4 5 6 | mysqld_pid=` cat "$mysqld_pid_file_path" ` if ( kill -0 $mysqld_pid 2> /dev/null ) then kill $mysqld_pid sleep 2 fi |
请完成MySQL启动脚本的编写,并实现可以使用chkconfig配置开机自启动。
要求:用函数,case语句、if语句等实现。
解答:此题的技巧适合绝大多数启动脚本,例如:rsync,nginx等,仅以MySQL为例介绍思路。
简单、易用、高效、专业
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | #!/bin/bash # chkconfig: 2345 64 36 # description: MySQL startup #Author:oldboy #Blog:http://oldboy.blog.51cto.com #Time:2017-07-07 09:24:34 #Name:mysqld #Version:V1.0 #Description:This is a test script. [ -f /etc/init .d /functions ] && source /etc/init .d /functions bindir= "/application/mysql/bin" datadir= "/application/mysql/data" mysqld_pid_file_path= "/application/mysql/`hostname`.pid" PATH= "/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin" #此步对开机启动及定时启动及其关键。 export PATH return_value=0 # Lock directory. lockdir= '/var/lock/subsys' lock_file_path= "$lockdir/mysql" log_success_msg(){ echo " SUCCESS! $@" # 注意函数的缩进,下同,也是专业的表现,可放到functions里。 } log_failure_msg(){ echo " ERROR! $@" } # Start Func start(){ # Start daemon echo "Starting MySQL" if test -x $bindir /mysqld_safe # 启动文件是否可执行。 then $bindir /mysqld_safe --datadir= "$datadir" --pid- file = "$mysqld_pid_file_path" > /dev/null & return_value=$? # 是否处理好返回值是区别脚本是否专业规范的关键。 sleep 2 # Make lock for CentOS if test -w "$lockdir" # 锁目录是否可写。 then touch "$lock_file_path" # 创建锁文件。 fi exit $return_value else log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)" fi } # Stop Func stop(){ if test -s "$mysqld_pid_file_path" # 是否PID文件存在并大小大于0。 then mysqld_pid=` cat "$mysqld_pid_file_path" ` if ( kill -0 $mysqld_pid 2> /dev/null ) # 检查PID对应的进程是否存在。 then echo "Shutting down MySQL" kill $mysqld_pid # 不能带-9,否则后果自负。 return_value=$? sleep 2 else log_failure_msg "MySQL server process #$mysqld_pid is not running!" rm -f "$mysqld_pid_file_path" fi # Delete lock for Oldboy's CentOS if test -f "$lock_file_path" then rm -f "$lock_file_path" fi exit $return_value else log_failure_msg "MySQL server PID file could not be found!" fi } case "$1" in start) start ;; stop) stop ;; restart) if $0 stop; then $0 start else log_failure_msg "Failed to stop running server, so refusing to try to start." exit 1 fi ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 esac exit $return_value #是否处理好返回值是区别脚本是否专业规范的关键。 |
保留原著出处:http://oldboy.blog.51cto.com/2561410/1945183
感谢作者分享、