53

I'm working on a tiny dropbox-like bash script, how can I compare the dates of 2 files and replace the old one(s) with the new one without using rsync is there any simple way to process this? can the SHA1 help me with knowing the newer?

kvantour
  • 25,269
  • 4
  • 47
  • 72
Wael hamadeh
  • 755
  • 1
  • 6
  • 14

4 Answers4

128

You can compare file modification times with test, using -nt (newer than) and -ot (older than) operators:

if [ "$file1" -ot "$file2" ]; then
    cp -f "$file2" "$file1"
fi
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
9

Here is a POSIX solution:

find -name file2 -newer file1
Zombo
  • 1
  • 62
  • 391
  • 407
6

Or even shorter and nicer, look at man stat:

stat -c %y file
whatever4711
  • 61
  • 1
  • 1
  • 3
    Use %Y for seconds since epoch, much easier to use. – bugmenot123 Apr 20 '19 at 22:01
  • This is not portable, though. POSIX `stat` has a rather depressingly narrow set of options. – tripleee Aug 29 '19 at 06:21
  • 1
    For anyone else running into this problem: If `FILE` is a symlink to another file, then `stat -c %Y FILE` will output the last-modified-date of the *symlink*, not the file the link is pointing at. Use `stat -L -c %Y FILE` in this case. – balu Oct 09 '19 at 23:45
2

how about

 stat file|awk -F': ' '/Modify: /{print $2}'
Kent
  • 189,393
  • 32
  • 233
  • 301
  • This one helped me out with what I was trying to accomplish. Now, how to compare those times? I'm using the answers found here: http://stackoverflow.com/questions/8116503/how-to-compare-two-datetime-strings-and-return-difference-in-hours-bash-shell Perfect! – harperville Dec 31 '13 at 16:11