PDA

View Full Version : Compare file creation dates in bash script?


frankloaf
07-10-2004, 03:38 PM
Is it possible to compare file creation dates in a bash script? I want to do something like:

if file1date > file2date then
cp file1 file2
else
cp file2 file1


thanks.

jbc
07-10-2004, 06:43 PM
The -nt and -ot conditional expressions for bash compare files using the modified date. The creation date seems completely foreign to the BSD subsystem as near as I can tell; none of the standard tools seem able to access this date (hope someone proves me wrong here).

Think your best bet may be to use the SetFile command from Xcode (or the Developer's Tools for older systems) to get the creation dates for your files. You can then compare them in your condition. More complicated than it should be.

frankloaf
07-11-2004, 05:35 PM
The modification date would be OK for my purposes. I'm kind of a newbie to scripting... How would I use those conditionals in the script?

The -nt and -ot conditional expressions for bash compare files using the modified date. The creation date seems completely foreign to the BSD subsystem as near as I can tell; none of the standard tools seem able to access this date (hope someone proves me wrong here).

Think your best bet may be to use the SetFile command from Xcode (or the Developer's Tools for older systems) to get the creation dates for your files. You can then compare them in your condition. More complicated than it should be.

jbc
07-11-2004, 06:27 PM
Ah. Well, within the context of what you have, you could use something like:

#!/bin/bash
if test "/path/to/file1" -nt "/path/to/file2"
then
cp "/path/to/file1" "/path/to/file2"
else
cp "/path/to/file2" "/path/to/file1"
fi

"-nt" is "newer than"; "-ot" is "older than". Both are based on the date the files were last modified, as I mentioned. Page through "man bash" in Terminal until you get to the "Conditional Expressions" section to read about these options in bash. Or see "man test" for the non-builtin version, which has the same options, I think.

I suspect this might be better done with rsync, but I'm still a bit confused about using rsync for two-way synchronization of files. Also rsync will trash resource forks of files, so you need to be careful about what sorts of files you're working with.