Folder Trigger, activate applescript but use the added file in the script

I'm looking to have a Folder to trigger an action when a file is added, how do I then pass that filename onto the applescript?

My initial response is "Use Hazel" but I presume that isn't what you're looking for. :wink:

The only way that I can think of is to use a shell script to get the most recently changed file in the directory.

ls -1rt /path/to/your/folder | tail -1

which will get you something like This File.ext

Note that it will not include the folder path, just the file name.¹

Save the output of that shell script to a variable, and then you can use the variable in AppleScript.

(There's probably a way to do that in AppleScript too, but I don't know AS well enough to know what it is.)

¹ it also occurs to me that this will just give you the most-recently-modified file, which may not be the most-recently-ADDED file. For example, imagine that you made a file on Monday called "~/Desktop/test1.txt" and then a file on Tuesday called "~/Documents/test2.txt". If you moved test1.txt to the ~/Documents/ folder, ls -1rt ~/Documents/ | tail -1 will give you test2.txt

Then there's the question of what do you do if the most recently added file is a folder. Do you want to take the same actions?

I tend to get around this by having "Files That I Want To Do Something Special To" all go to ~/Action/ which is where they are acted upon and then the final action is moving them to a different folder, so that ~/Action/ is (for all practical purposes) always empty, so whatever file / folder is in there is the only one that I need to act upon. Then I can either use Hazel or launchd to monitor that folder for changes.

I stick by my initial answer of "Use Hazel" as probably being the best/easiest solution.

I did find this,

Not working for me, but it does know what file triggered the action, unfortunately, it's not then running in a script.

I don't think applescript can run the recently added, only created and modify dates.

Easy.

MACRO:   Pass File Path from Folder Trigger to AppleScript [Example]


#### DOWNLOAD:
<a class="attachment" href="/uploads/default/original/3X/9/9/9902dfaadd9232550fc4952a10ff01261ebd2701.kmmacros">Pass File Path from Folder Trigger to AppleScript [Example].kmmacros</a> (3.0 KB)
**Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.**

---



![image|573x879](upload://b2wHQtzn3RluUpykXffKdPLw7fI.png)

### AppleScript 
```applescript
### Requires Keyboard Maestro 8.0.3+ ###

set kmInst to system attribute "KMINSTANCE"

tell application "Keyboard Maestro Engine"
  set filePath to getvariable "Local__FilePath" instance kmInst
end tell

--- filePath is the POSIX path to the file/folder ---
--  You may need to convert to Finder alias to use with Finder

set fileAlias to POSIX file filePath as alias

tell application "Finder" to open fileAlias
```
2 Likes

Perfect that it appears to work fine!! Thank you!

1 Like