運行系統命令而且將輸出寫到指定日志文件的shell腳本(2)


上一篇是個簡單的能夠運行而且寫入日志的腳本,可是假設放到生產環境上就顯得太粗糙了,所以須要進一步的優化:

#! /bin/bash

if [ -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
    fi
else
    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
    fi
fi
凝視: 

  1. [ -d "xxxx" ] 推斷文件夾路徑是否存在
  2. [ -f  "xxxx" ] 推斷文件是否存在
  3. touch 命令用於創建空文件。chmod 命令用於賦權。

特別注意:

  1. shell腳本對空格的要求異常的嚴格,必須注意空格,否則報錯了你查都非常難查。
  2. if 條件使用結束時必須有fi結尾。不然會報錯,也是非常難查了。

最后,這個是單詞運行的腳本,假設要循環運行的話加上上一篇寫的while true就可以。只是我採用的是類unix系統的計划任務管理器crontab來加入計划任務,讓系統按指定的計划時間來運行腳本。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM