老男孩教育Linux高端运维班Shell课后必会考试题:
企业Shell面试题10:开发企业级MySQL启动脚本
说明:
MySQL启动命令为:
/bin/sh mysqld_safe --pid-file=$mysqld_pid_file_path 2>&1 >/dev/null &
停止命令逻辑脚本为:
mysqld_pid=`cat "$mysqld_pid_file_path"` if (kill -0 $mysqld_pid 2>/dev/null)thenkill $mysqld_pidsleep 2 fi
请完成MySQL启动脚本的编写,并实现可以使用chkconfig配置开机自启动。
要求:用函数,case语句、if语句等实现。
解答:此题的技巧适合绝大多数启动脚本,例如:rsync,nginx等,仅以MySQL为例介绍思路。
简单、易用、高效、专业
#!/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 daemonecho "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 CentOSif test -w "$lockdir" # 锁目录是否可写。thentouch "$lock_file_path" # 创建锁文件。fiexit $return_valueelselog_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"fi } # Stop Func stop(){if test -s "$mysqld_pid_file_path" # 是否PID文件存在并大小大于0。thenmysqld_pid=`cat "$mysqld_pid_file_path"`if (kill -0 $mysqld_pid 2>/dev/null) # 检查PID对应的进程是否存在。thenecho "Shutting down MySQL"kill $mysqld_pid # 不能带-9,否则后果自负。return_value=$?sleep 2elselog_failure_msg "MySQL server process #$mysqld_pid is not running!"rm -f "$mysqld_pid_file_path"fi# Delete lock for Oldboy's CentOSif test -f "$lock_file_path"thenrm -f "$lock_file_path"fiexit $return_valueelselog_failure_msg "MySQL server PID file could not be found!"fi } case "$1" instart) start;;stop)stop;;restart)if $0 stop; then$0 startelselog_failure_msg "Failed to stop running server, so refusing to try to start."exit 1fi;;*)echo "Usage: $0 {start|stop|restart}"exit 1 esac exit $return_value #是否处理好返回值是区别脚本是否专业规范的关键。
更多Shell知识可参考老男孩的新书《跟老男孩学Linux运维:Shell编程实战》,各大书店有售
https://item.jd.com/12117874.html
不妨先定个小目标,精通Shell编程!如果精通了,则15K起,可联系老男孩给你推荐企业。
有精力的朋友可以写下rsync或nginx启动脚本模仿下,可以评论在下面。