標籤:指令碼 shell linux unix
上一篇是個簡單的可以執行並且寫入日誌的指令碼,但是如果放到生產環境上就顯得太粗糙了,所以需要進一步的最佳化:
#! /bin/bashif [ -d "/opt/bmc" ] ; then if [ -f "/opt/bmc/usysfault.log" ] ; then { date +"%Y-%m-%d %H:%M:%S" /usr/lpp/diagnostics/bin/usysfault #要執行的命令的絕對路徑 } > /opt/bmc/usysfault.log #要存放記錄檔的絕對路徑 else touch /opt/bmc/usysfault.log chmod 755 /opt/bmc/usysfault.log { date +"%Y-%m-%d %H:%M:%S" /usr/lpp/diagnostics/bin/usysfault } > /opt/bmc/usysfault.log fielse if [ -f "/tmp/usysfault.log" ] ; then { date +"%Y-%m-%d %H:%M:%S" /usr/lpp/diagnostics/bin/usysfault } > /tmp/usysfault.log else touch /tmp/usysfault.log chmod 755 /tmp/usysfault.log { date +"%Y-%m-%d %H:%M:%S" /usr/lpp/diagnostics/bin/usysfault } > /tmp/usysfault.log fifi
注釋:
- [ -d "xxxx" ] 判斷目錄路徑是否存在
- [ -f "xxxx" ] 判斷檔案是否存在
- touch 命令用於建立空檔案,chmod 命令用於賦權。
特別注意:
- shell指令碼對空格的要求異常的嚴格,必須注意空格,否則報錯了你查都很難查。
- if 條件使用結束時必須有fi結尾,不然會報錯,也是很難查了。
最後,這個是單詞執行的指令碼,如果要迴圈執行的話加上上一篇寫的while true即可。不過我採用的是類unix系統的計劃工作管理員crontab來添加計劃任務,讓系統按指定的計劃時間來執行指令碼。
執行系統命令並且將輸出寫到指定記錄檔的shell指令碼(2)