获取Linux中文件最后修改时间的状态

获取Linux中文件最后修改时间的状态

我正在尝试获取 Linux 中文件是否被修改的状态。我正在使用这段代码,它运行良好,但它有一个问题,即它在第一个“if”语句后退出。

它不查找 elif 语句。我试图在文件在过去 2 分钟内未修改时获得“警告”,如果文件在 4 分钟内仍未修改,它应该给我“严重”。它总是显示警告或 OK,但没有考虑 elif 语句。我正在使用的代码

#!/bin/bash
# How to execute ./sensor.sh tem_sensor
HOUR=$(date +%H)
MIN=$(date +%M)

# Directory where they are sensor directorys
DIR=/home/robbin/Desktop/sensor_collection/
# Name of selected sensor
SENSOR=$1
# Name of sensor's directoris
SENSORS=(sensor1)

# Loop in every folder
for i in ${SENSORS[@]}
do
        # We only want the specified sensor so we will skip until we found it
        if [[ $SENSOR != $i ]]; then continue ; fi
        # You take the hour and minute value from last file
        LHOUR=$(ls -lrt $DIR/$i| tail -n1 | awk '{ print $8}' | awk -F ':' '{ print $1}')
        LMIN=$(ls -lrt $DIR/$i | tail -n1 | awk '{ print $8}' | awk -F ':' '{ print $2}')
        # We calculate the diferences
        let FHOUR=$(( HOUR - LHOUR ))
        let FMIN=$(( MIN - LMIN ))

        # if the diference is greater than 2
        if ([ $FMIN -gt 02 ] && [ $FMIN -lt 04 ]); then
            echo "WARNING - More than 2 minutes without recieving data"
            exit 1 # We put warning!
        # Else if it is not more than 2
        # We check if we have an hour of diference!
        elif [[ $FMIN -gt 04 ]]; then
            echo "CRITICAL - More than 4 minutes without recieving data"
            exit 2 # We put Red alert!
        else
            echo "OK - We recieve data"
            exit 0 # Green alert if we dont have problems
        fi
done
echo "UNKNOW - Sensor not found"
exit 3

如果有人能帮我解决这个问题。cox 看起来没有问题,应该可以正常工作。我是 Bash 脚本的新手。我将不胜感激。

答案1

您可以按如下方式重新排列 if-else 语句:

if [[ $FMIN -gt 04 ]]; then
    echo "CRITICAL - More than 4 minutes without recieving data"
    exit 2 # We put Red alert!
elif [[ $FMIN -gt 02 ]]; then
    echo "WARNING - More than 2 minutes without recieving data"
    exit 1 # We put warning!
else
    echo "OK - We recieve data"
    exit 0 # Green alert if we dont have problems
fi

这更容易阅读,而且可以满足您的需要。

答案2

您需要交换 if 和 elif 子句中的条件。第一个条件符合两种情况,因此第二个条件永远不会被检查。

相关内容