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?
Asked
Active
Viewed 4.5k times
53
-
It really depends on what you mean by the "date of a file". You are probably referring to `mtime`, but specificity is good. – William Pursell Feb 10 '13 at 21:32
-
@WilliamPursell, the last modify i mean – Wael hamadeh Feb 10 '13 at 21:34
-
For the record, the SHA1 absolutely does not reveal anything about the file's age, or name, or contents. – tripleee Sep 22 '21 at 04:22
4 Answers
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
-
7that's awesome :))) never thought the simple compare could do the job since i'm new to centOS :) thank u :) – Wael hamadeh Feb 10 '13 at 21:41
-
-
@JoeC I tested and if same age returned 1 (after `touch -r ...`) – Aquarius Power Feb 06 '15 at 18:31
-
-
If the files are the same, -ot and -nt return false (1). An absent file is treated as older than a present file. – mwfearnley Mar 18 '22 at 13:10
6
Or even shorter and nicer, look at man stat
:
stat -c %y file

whatever4711
- 61
- 1
- 1
-
3
-
This is not portable, though. POSIX `stat` has a rather depressingly narrow set of options. – tripleee Aug 29 '19 at 06:21
-
1For 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