2014-06-15 66 views
0

我寫這個劇本,它檢查是否AA某些文件已被更改:IF中的變量是否可以在IF外的變量上投影?

#!/bin/bash 
path=$1 
if [ -z "$path" ]; then 
    echo "usage: $0 [path (required)]" 1>&2 
    exit 4 
fi 

lastmodsecs=`stat --format='%Y' $path` 
lastmodsecshum=`date -d @$lastmodsecs` 
basedate=$newdate 
if [ $lastmodsecs != $basedate ]; then 
     echo "CRITICAL: $path was last modified on $lastmodsecshum !" 
     newdate=`stat --format='%Y' $path` 
     exit 1 
else 
    echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)" 
    exit 0 
fi 

萬一IF聲明是真實的我想設置$ newdate變量與UNIX時間在最後一次更改後項目它到了剛好在IF之上的基於$的變量,這可能嗎?

Serge: 腳本現在看起來像這樣,結果是,如果文件已被更改,則檢查狀態保持爲CRITICAL:/ etc/passwd最後修改爲date,由於某種原因,$ persist文件沒有正確更新:

#!/bin/bash 
path=$1 
if [ -z "$path" ]; then 
    echo "usage: $0 [path (required)]" 1>&2 
    exit 4 
fi 
lastmodsecs=`stat --format='%Y' $path` 
lastmodsecshum=`date -d @$lastmodsecs` 
persist="/usr/local/share/applications/file" 
if [ -z $persist ] 
     then newdate=`stat --format='%Y' $path` 
else read newdate < $persist 
fi 
basedate=$newdate 
if [ $lastmodsecs != $basedate ]; then 
     echo "CRITICAL: $path was last modified on $lastmodsecshum !" 
     echo $lastmodsecs > $persist 
     exit 1 
else 
    echo "OK: $path hasn't been modified since $lastmodsecshum \(supervized change\)" 
    exit 0 
fi 
+0

你是什麼意思與'項目',分配? – PeterMmm

+0

是的,這可能是我不知道正確的術語...可以分配。 –

+0

那麼在設置新日期之後,您想如何使用基礎?您不會在腳本中使用基礎。 – PeterMmm

回答

0

它看起來像你的代碼需要在環與newdate是最初從上次運行值運行。通常情況下,這可能正常工作,如果循環是在腳本:

... 
# newdate first initialisation 
newdate=`stat --format='%Y' $path` 
while true 
    do lastmodsecs=`stat --format='%Y' $path` 
    lastmodsecshum=`date -d @$lastmodsecs` 
    basedate=$newdate 
    if [ $lastmodsecs != $basedate ]; then 
      echo "CRITICAL: $path was last modified on $lastmodsecshum !" 
      newdate=$lastmodsecs 
      exit 1 
    else 
     echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)" 
    fi 
done 

但是,當我看到你的exit 0exit 1這個腳本也意在狀態返回到調用者。您不能使用環境,因爲程序不允許修改其父級環境。所以唯一的可能是由調用者管理newdate,或者將其保存到文件中。這最後一個是容易的,需要在主叫方沒有修改:

... 
persist=/path/to/private/persist/file 
# eventual first time initialization or get newdat from $persist 
if [ -z $persist ] 
then newdate=`stat --format='%Y' $path` 
else read newdate < $persist 
fi 
... 
basedate=$newdate 
if [ $lastmodsecs != $basedate ]; then 
     echo "CRITICAL: $path was last modified on $lastmodsecshum !" 
     echo $lastmodsecs > $persist 
     exit 1 
else 
    echo "OK: $path hasn't been modified since $lastmodsecshum \(last supervized change\)" 
    exit 0 
fi 

當然測試是你的,你說話的Nagios ...

+0

謝謝,我用腳本的結果編輯了我的問題。 –

0

對於檢查文件日期是否比去年的最近一次更檢查,試試這個:

#!/bin/bash 
lastchecked="/tmp/lastchecked.state"  
file="/my/file" 

# compare file date against date of last check 
[[ "$file" -nt "$lastchecked" ]] && echo "$file has been modified since last check" 

# remember time when this check was done 
touch "$lastchecked"