標籤:linux shell編程 shell 函數 shell 函數參數傳遞 處理依賴關係 shell 函數傳回值
問題通用情境描述:測試伺服器上的服務眾多,為了避免過大的資源開銷將原先的服務都設定為開機不啟動,僅保留一些必要的系統服務,因此當需要使用哪些服務時需要手動開啟。有的服務對其他服務可能存在依賴關係,例如服務A依賴服務B,服務B依賴服務C。此時可以用順序執行的方式解決依賴問題,如果檢查到依賴不滿足,則退出執行。
編碼思路:
(一)為什麼使用函數?
1.當有重複代碼或 當一個任務只需要很少的修改就被重複幾次執行時, 這時你應考慮使用函數.
2.函數可以處理傳遞給它的參數並且能返回它的退出狀態代碼(exit status)給指令碼後續使用.
(二)函數參數如何傳遞的?
函數以位置來引用傳遞過來的參數(就好像他們是位置參數(positional parameters)), 例如$1,$2以此類推.
(三)如何處理依賴關係?
用順序執行的方式解決依賴問題,如果檢查到依賴不滿足,則退出執行。
編碼範例:
#!/bin/bashREQUIRED_SERVICE_1=mysqlREQUIRED_SERVICE_2=zabbix-serverREQUIRED_SERVICE_3=zabbix-agentfunction help(){echo "Function: start\stop zabbix service and dependence, and check status"echo "Usage: $0 {start|stop|status|help}"}function check_service_if_is_running(){SERVICE=$1service $SERVICE status >/dev/null 2>&1REVAL=$?if [[ $REVAL -eq 0 ]]; thenreturn 0elsereturn 1fi}function start_service_if_is_stoped(){SERVICE=$1service $SERVICE start >/dev/null 2>&1check_service_if_is_running $SERVICEREVAL=$?if [[ $REVAL -eq 0 ]]; thenecho $SERVICE is running...elseecho $SERVICE is not running, error code is $REVAL.exit 1fi}function stop_service_if_is_running(){SERVICE=$1service $SERVICE stop >/dev/null 2>&1check_service_if_is_running $SERVICEREVAL=$?if [[ $REVAL -eq 1 ]]; thenecho $SERVICE is stoped...fi}function status_service(){SERVICE=$1check_service_if_is_running $SERVICEREVAL=$?if [[ $REVAL -eq 0 ]]; thenecho $SERVICE is running...elseecho $SERVICE is not running, error code is $REVAL.exit 1fi}function start(){start_service_if_is_stoped $REQUIRED_SERVICE_1start_service_if_is_stoped $REQUIRED_SERVICE_2start_service_if_is_stoped $REQUIRED_SERVICE_3}function stop(){stop_service_if_is_running $REQUIRED_SERVICE_3stop_service_if_is_running $REQUIRED_SERVICE_2stop_service_if_is_running $REQUIRED_SERVICE_1}function status(){status_service $REQUIRED_SERVICE_1status_service $REQUIRED_SERVICE_2status_service $REQUIRED_SERVICE_3}case "$1" in start)start;;stop)stop;;status)status;;*)helpexit 1;;esac
編碼測試:
650) this.width=650;" title="image" style="border-top:0px;border-right:0px;border-bottom:0px;border-left:0px;" border="0" alt="image" src="http://s3.51cto.com/wyfs02/M01/5A/31/wKiom1T5GSzR8vkuAAE_QcC1nfg612.jpg" height="265" />
--END--
本文出自 “通訊,我的最愛” 部落格,請務必保留此出處http://dgd2010.blog.51cto.com/1539422/1617846
Linux手動啟動、停止多個服務用的shell指令碼