1. 程式人生 > >linux shell 之嘗試編寫 企業級 啟動腳本

linux shell 之嘗試編寫 企業級 啟動腳本

nginx data err 企業級 開機自啟 註意 sbin 分享 fin

企業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

感謝作者分享、

linux shell 之嘗試編寫 企業級 啟動腳本