10 Replies Latest reply: Jul 24, 2014 7:47 PM by pickupb
rajaharish Level 1 (0 points)


I am trying to get a latest added file from a folder..and for this i have below script


tell application "Finder"

    set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias

    set fileName to latestFile's name

end tell


By using this i am not able to get latest file because for some files the creation date is some older date so is there any way to get latest file based on "Date Added" column of a folder.

  • Camelot Level 8 (46,675 points)

    You can't do this in the way you're tryng, because the sort command can sort data based on any property, but the date a file was added to a folder is not part of the file's data - it's part of the metadata associated with the folder itself, and the Finder doesn't expose that data to AppleScript.


    What is it you're trying to achieve? At face value, without knowing more data, you might be able to solve the problem via Folder Actions, which are AppleScripts that fire when a folder is modified in some way (e.g. opened, closed, added to or deleted from). You may be able to write a Folder Action that affects new files as they are added to the folder, or at the very least create a manual record of the last file added that you can later affect.

  • rajaharish Level 1 (0 points)

    Can i get llast added file from a folder using terminal command ls?

  • BobHarris Level 6 (17,724 points)

    The 'ls' command only has options to sort files vis modification date, last accessed time, and the last time the file's metadate was modified (frequently the same as modification time, but not always, such as when the file's permissions are changed, but the file data is unchanged).


    I think Camelot's suggest to use a Folder Action is your best bet.  For example, create a folder action that changes the modification (mtime) or metadata change time (ctime) when a new files is added to the directory (I'm assuming a folder action can be told which files are being touched when the folder action triggers).


    Or have your script maintain a list of previously seen files, and then check the current files against the list, and any file not in the list must be new (or it was renamed).  After getting your new file(s), update your list.  Of course if you have multiple added new files you would be handed more than 1 file to handle.

  • Camelot Level 8 (46,675 points)

    Not via ls, no. If you're opposed to a Folder Action the closest you can get is using mdls to extract the 'Date Added' metadata and (manually) sort on that. For example:

    $ mdls -name kMDItemFSName -name kMDItemDateAdded ~/*

    This command will list the name and date added of every file in your home directory. You'd need to parse that data and sort it to find the most recent item. Not trivial, but all I can think of off-hand. To me, that Folder Action is looking more and more appealing by the minute

  • Pierre L. Level 5 (4,255 points)

    If you don't mind using GUI Scripting (you must enable access for assistive devices in the Accessibility System Preference pane), the following script should give you a reference to the last item added to any folder. Admittedly not the most elegant solution, but it works, at least under OS X 10.8.2.




    set theFolder to choose folder


    tell application "Finder"


        set theFolderWindow to container window of theFolder

        set alreadyOpen to exists theFolderWindow

        tell theFolderWindow


            set theInitialView to current view

            set current view to icon view

        end tell

    end tell


    tell application "System Events" to tell process "Finder"

        -- Arrange by None:

        set theInitialArrangement to name of menu item 1 of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is ""

        keystroke "0" using {control down, command down}


        -- Sort by Date Added:

        set theInitialSortingOrder to name of menu item 1 of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is ""

        keystroke "4" using {control down, option down, command down}


        -- Get the name of the last item:

        set theItemName to name of image 1 of UI element 1 of last scroll area of splitter group 1 of (window 1 whose subrole is "AXStandardWindow")


        -- Restore the initial settings:

        click menu item theInitialSortingOrder of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1

        click menu item theInitialArrangement of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1

    end tell


    tell application "Finder"

        set current view of theFolderWindow to theInitialView -- restore the initial view

        if not alreadyOpen then close theFolderWindow

        set theLastItem to item theItemName of theFolder

    end tell





    Message was edited by: Pierre L.

  • twtwtw Level 5 (4,925 points)

    Another option is to use a folder action or launchd item reset the creation or modification date to the current date whenever a file is added to the folder.  e.g.:


    on adding folder items to this_folder after receiving these_items

              tell application "System Events"

                        repeat with this_item in these_items

                                  set modification date of this_item to (current date)

                        end repeat

              end tell

    end adding folder items to


    That way sorting by modification date is the same as sorting by file addition date.  You'll have to work out how to handle when multiple files are added at the same time, of course.

  • Peter Payne Level 1 (5 points)

    Just chiming in on this, in case anyone is still paying attention. Oddly 10.9 Mavericks seems to give the oldest file, not the newest file. Did something like


    tell application "Finder"

              set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias

              set fileName to latestFile's name

    end tell


    return the newest file before? Because it's showing the oldest now.

  • Pierre L. Level 5 (4,255 points)

    Under Mavericks, this solution still returns the last added file (which of course has nothing to do with the creation or modification date).

  • LogicProLetsGo Level 1 (0 points)

    I do it like this:

    Return List of Aliases for Items based on Time Added to Folder.scpt


    set dirSel to path to home folder

    set filteredList to my listFilesTimeOfCreation(dirSel, 1000) -- positive Input


    repeat with theItem in filteredList

      get theItem as string

    end repeat


    on listFilesTimeOfCreation(dirInputAlias, timeAgoPositiveIntegerInMinutes)

      -- Returns list

      set timeInterval to timeAgoPositiveIntegerInMinutes * 60 * 60 - 1 -- convert to negative number (time past, not time into future) and convert to minutes-- ## -5 * 60 -- 1 measured in milliseconds e.g. -1*60 = 1 minute ago

      -- 5 minutes ago = -5 * 60

      set filteredList to {}


      -- Check downloads folder and list files older than N minutes.

      set locateDateAdded to "mdfind -onlyin " & quoted form of POSIX path of dirInputAlias & " 'kMDItemDateAdded>$time.now(" & timeInterval & ")&&kMDItemFSName=\"*.*\"c'"

      set filteredItemsOutput to do shell script locateDateAdded


      tell application "Finder"

      repeat with itemStep from 1 to count of paragraphs of filteredItemsOutput

      set thisItem to paragraph itemStep of filteredItemsOutput

      set end of filteredList to POSIX file thisItem as alias

      end repeat

      end tell

      return filteredList -- list of aliases

    end listFilesTimeOfCreation


  • pickupb Level 1 (0 points)

    Hi Rajaharish,


    I know this is a bit late, but I ran into this problem, tried the code below and it worked.  For Mavericks, I just changed it to the "Last item" instead of item 1.



    tell application "Finder"

      set latestFile to the last item of (sort (get files of (path to downloads folder)) by creation date) as alias

      set fileName to latestFile's name

      display dialog "the file's name is: " & fileName

    end tell