In shell, how can I tail the latest file created in a directory?
|
migrated from stackoverflow.com Mar 8 '10 at 19:17
|
No no no! Do not parse the output of ls! If you must do this I would recommend find
Or anything that isn't ls. Parsing the output of ls is difficult and unreliable. EDIT: added -maxdepth 1 per the comments. Don't code in haste! |
|||||||||||||||||||||
|
If you're worried about filenames with spaces,
|
|||||||||
|
|
On POSIX systems, there is no way of getting the "last created" directory entry. Each directory entry has So the best you can get is to "tail the last recently modified file", which is explained in the other answers. I would go for this command: tail -f "$(ls -tr | sed 1q)" Note the quotes around the |
|||||
|
|
|
You can use:
The The output of that command (the most recent file) is then passed to Keep in mind this runs the risk of getting a directory if that's the most recent directory entry created. I've used that trick in an alias to edit the most recent log file (from a rotating set) in a directory that contained only those log files. |
|||||||||||
|
|
There are probably a million ways to do this, but the way I would do it is this:
The bits between the backticks (the quote like characters) are interpreted and the result returned to tail.
|
|||
|
|
|
A simple:
works just fine for me. The problem is to get files that are generated after you started the tail command. But if you don't need that (as all the solutions above do not care for it), the asterisk is just simpler solution, IMO. |
|||
|
|
|
|||
|
|
|
Someone posted it, and then erased it for some reason, but this is the only one that works, so...
|
|||||||||
|
Explanation:
|
|||||||||
|