My question is similar to this one. Except the file I want to check the date of is on a remote server that I ssh onto/scp off of. Basically I want to be able to compare the date a file was last modified on both my local machine and a remote server, and whichever one is newer copy to the other computer. I know how to do all the copying and stuff I just want to figure out how to compare the dates.
Asked
Active
Viewed 2,354 times
0
-
2["What is the XY problem?"](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Ignacio Vazquez-Abrams Aug 14 '15 at 21:56
-
2Take a look at `man rsync`. – Cyrus Aug 14 '15 at 22:03
-
@cyrus I looked at rsync briefly but I want to be able to do this bi-directionally. I looked at the osync project but it seemed like it was overkill, so I thought id just program my own. The only problem I'm running into is knowing which file is most recent over ssh – Kieran Ramnarine Aug 14 '15 at 22:21
-
@IgnacioVazquez-Abrams I know my X problem, I just need to tackle this date part for my solution to work. It's more education than function I guess – Kieran Ramnarine Aug 14 '15 at 22:22
1 Answers
2
Try this:
remote=$(ssh user@server "stat -c %Y /path/to/remote_file")
[[ -z "$remote" ]] && exit 1 # stop on error ($remote is empty)
local=$(stat -c %Y /path/to/local_file)
if [[ $remote -gt $local ]]; then
echo remote file is newer
else
echo local file is newer
fi

Cyrus
- 84,225
- 14
- 89
- 153
-
Good deal. I might use `printf %q` to escape the path to the remote file so we don't convert tricksy filenames like `/tmp/$(rm -rf /)/hello` to commands, but this is pretty much spot on. – Charles Duffy Aug 14 '15 at 22:35
-
...example: `printf -v quoted_filename %q "$filename"; ssh user@server "stat -c %Y $quoted_filename"` – Charles Duffy Aug 14 '15 at 22:37
-
-
-
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:44