Sunday, October 9, 2022

[SOLVED] How to open the most recent file in a folder using Terminal (Unix commands)

Issue

I am trying to implement this as an Automator action. I would like to open the most recent file added to the Downloads folder. Is this possible? Thanks.

id='dv3'>

Solution

For shell scripts, you can use the Run Shell Script action in your Automator workflow.

Most utilities use the modification time, but ls can be used to sort by creation date. Adapted from a couple of StackExchange topics, you can use something like the following (replace the action’s default script):

open "$(find ~/Downloads -type f -not -path '*/.*' -exec ls -Ut {} + | head -1)"

The above statement uses find to get files (but not dot files) in the user’s Downloads folder, passes them on to ls to sort by the creation time, and then gets the first one for the open command.

If there aren’t any files found, a Finder window will be opened to the user’s home folder.



Answered By - red_menace
Answer Checked By - Clifford M. (WPSolving Volunteer)