2014-06-15 34 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"