Search code examples
shellbatch-filemakefilenmake

How to get the last created file, among a list of file names


Problem

I have this Makefile to be run by the Windows NMAKE tool:

push:
    cd dist
    "C:\Program Files\Rhino 7\System\Yak.exe" push myapp-*.yak

The above statement throws a fatal error. Since the Yak.exe tool expects a full path/name of the file.

Question

There is a dist subfolder containing files like:

  • myapp-1.2.0-rh7_13-win.yak
  • myapp-1.3.0-rh7_13-win.yak
  • myapp-1.4.0-rh7_13-win.yak
  • ...

How can I programmatically get the full name of the last created file? I'm looking for a simple Windows batch script that I can implement inside my Makefile, ideally.

Options

I'm playing around with some options. But I cannot figure out how to actually implement them. At least two approaches can determine the last created file:

  1. The largest version numbers of L, M and N inside this pattern: myapp-L.M.N-*-win.yak
  2. The timestamp.
  3. ...?

UPDATE

With the help of @Stephan I implemented this approach.

push:
    cd dist
    for /f "delims=" %%i in ('dir /b /od /a-d myapp-*-win.yak') do set LAST=%%i
    "C:\Program Files\Rhino 7\System\Yak.exe" push "%LAST%"

I'm on the right track. But it has a problem. The %LAST% variable is not properly passed from the for loop to the push statement. I'm not sure how to pass the variable properly.

Also, using do set "LAST=%%i" has the same problem as do set LAST=%%i


Solution

  • This approach finally worked:

    push:
        cd dist
        echo off > temp.bat
        for /f "delims=" %%i in ('dir /b /od /a-d myapp-*-win.yak') do echo "C:\Program Files\Rhino 7\System\Yak.exe" push "%%i" > temp.bat
        call temp.bat
        del temp.bat
    

    A temporary batch file temp.bat is created. For each myapp-*-win.yak file, a statement is written to temp.bat, overwriting the previous statement. Therefore, after the loop, temp.bat contains the statement for the latest file.

    I'm not sure if this is the best approach. However, it works so far.