Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


Detect the newest file in a specific folder and pass it as an argument to another process. The first argument to your program will be the folder, and the second argument will be the full path to the process.

Please specify the platform(s) your code works on.



newestfile "C:\Public_domain_movies\" "C:\Mplayer\mplayer.exe"


./newestfile /home/user /bin/ls
share|improve this question
@Geobits I expect the most recent timestamp no matter what, I removed the misleading part. – Eduard Florinescu Jul 2 '14 at 15:42
Actually I think it could have added a very interesting twist to have to figure out when the program was last run. – Martin Ender Jul 2 '14 at 15:48
@Ventero Yes, no recursive scanning just the specified folder – Eduard Florinescu Jul 2 '14 at 17:34
The most recently modified file or the most recently created file? – Joey Jul 2 '14 at 18:05
@Joey The most recently modified – Eduard Florinescu Jul 2 '14 at 18:09
up vote 4 down vote accepted

Zsh - 15

Only tested on Linux, but it should work on other platforms too.

$2 $1/*(.om[1])
share|improve this answer

Windows, PowerShell, 35

&$args[1](ls $args[0]|sort *w*)[-1]
share|improve this answer

Linux, Ruby, 52 characters


I'm not sure if I undestood the specifications correctly, so if this doesn't work as intended, please let me know. I only tested this on Linux, but in theory it should run on Windows, too.

share|improve this answer

linux - bash+sed - 18 bytes

$2 `ls -t $1|sed q`

Does not work if the arguments contain blanks.

share|improve this answer

Windows, cmd, 54

for /f "delims=" %%A in ('dir/b/o-d %1')do %2 %%A&exit


  • Closes the current shell session
  • Will consider directories (as do most other solutions)
share|improve this answer
You don't need the options string "delims=" – nderscore Jul 2 '14 at 18:34
Well, have fun with file names with spaces, then. – Joey Jul 2 '14 at 18:34
This doesn't work if the file has spaces in it – Eduard Florinescu Jul 2 '14 at 19:12
What if you add /x parameter for short names? FOOBAR~1.TXT – nderscore Jul 2 '14 at 19:13
@nderscore: Not every file has to have a short name. – Joey Jul 2 '14 at 19:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.