如何根据文件日期的比较有条件地执行bash代码?

时间:2012-02-13 20:52:42

标签: bash scripting

我正在尝试做这样的事情:

for f in $SOMEDIR
    do
        if "$f is newer than some other file"
        then
             "do this"
        else
             "do this"
        fi
    done
fi

我知道我已经看到了一种快速比较文件日期并执行的好方法,如果第一个文件日期恰好比第二个更新,但我不知道在哪里可以再找到它。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:2)

使用文件测试操作符。

取自:http://tldp.org/LDP/abs/html/fto.html

f1 -nt f2
文件f1比f2

更新

f1 -ot f2
文件f1早于f2

假设test和test2是文件。

if [[ "test" -nt "test2" ]]; then
    echo "yes"
else
    echo "no"
fi

if [[ "test" -ot "test2" ]]; then
    echo "yes"
else
    echo "no"
fi

执行时:

 $ ./test
 yes
 no