0

In a cmd script (is this the same as a batch script?) I want to execute a command only if file1 is newer than file2. Both files reside in the same directory.

I found many things on SO but none do exactly what I need, or do it in a very roundabout way or don't consider localization.

Just something like this:

if "%file1%" is_newer_than "%file2%" (
  execute command
)
  • I do not want to find which file is newer.
  • I do not want to find the date of the newest file.
  • It must be locale-independent so no string manipulations of a formatted date allowed! (the script will be used around the globe)
  • The command itself is not date-aware, unlike the likes of xcopy.

This answer looks the most promising, but I have no idea how to use that function twice in an if statement.

Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
  • use it twice (generating two variables), *then* do your `if`. – Stephan Sep 04 '18 at 09:00
  • Your first question is asked and answered in [Windows batch files: .bat vs .cmd?](https://stackoverflow.com/questions/148968/) – Mofi Sep 05 '18 at 06:14

1 Answers1

2

dir /b /a:-d /o:d /t:w %file1% %file2% should sort files by time of write /o:-d reverse sort

for /f "tokens=*" %%? in ('dir /b /a:-d /o:d /t:w %file1% %file2%') do echo %%~tf? example show with timestamp

penknife
  • 101
  • 4
  • 1
    Great idea for the beginning of a simple solution. But it is important to note that this only works if both files are in the same folder because a separate sort is done for each folder. I realize the OP explicitly specified this condition, but I don't want others to mistakenly use this technique for files in different folders. – dbenham Sep 04 '18 at 22:08
  • One limitation - it does not tell you if two files have the exact same timestamp. I ran some quick tests, and it appears that files with identical timestamps appear in the same order if `/o-d` is used vs. `/od`. This fact could be used to identify when two files have the same timestamp. – dbenham Sep 04 '18 at 22:27
  • you can make new folder with soft-link to files(or just copy) and then do above – penknife Sep 06 '18 at 15:30