Bash: Check if file was modified since used in script

Posted by Thomas Münz on Stack Overflow See other posts from Stack Overflow or by Thomas Münz
Published on 2012-06-08T22:36:52Z Indexed on 2012/06/08 22:40 UTC
Read the original article Hit count: 259

Filed under:
|
|
|

I need to check in a script if a file was modified since I read it (another application can modify it in between). According to bash manual there is a "-N" test which should report if a file was modified since last read. I tried it in a small script but it seems like it doesn't work.

#!/bin/bash
file="test.txt"
echo "test" > $file
cat $file;
if [ -N $file ];
    then echo "modified since read";
else
    echo "not modified since read";
fi

I also tried an alternative way by touching another file and using

if [ "file1" -nt "file2 ];

but this works only on a seconds accuracy which may under rare conditions not be sufficient. Is there any other bash-inbuilt solution for this problem or I do really need to use diff or md5sum?

© Stack Overflow or respective owner

Related posts about file

Related posts about bash