OSX: Execute bash script when file appears in fold

2019-06-14 01:42发布

问题:

I'm attempting to script my own screenshot uploader.

I am nearly there: OSX: Automatically upload screenshot to imageBin and put URL in clipboard

That script lets me write:

upload_image foo.png

And it will upload it, put a link to the URL in my clipboard, and make a noise

But I want it to be automatic. As soon as foo.png appears on my desktop, I need to execute '~/upload_image.sh foo.png'

How can I do this?

I'm interested in a Bash solution as it would allow me to merge with the target script, so I would only have one script file, which is clean. Also it would be multiplatform. Getting it to launch on start-up would be an issue.

I'm also interested in an AppleScript solution; I think the following script may be close:

on adding folder items to this_folder after receiving theFiles

    -- If you want to do something with each file ...
    repeat with aFile in theFiles
        do shell script "~/upload_image.sh " & 
    end repeat

end adding folder items to

But I don't know how to pass 'aFile' into the command on the next line.

EDIT:

http://hardc0l2e.wordpress.com/2012/03/13/folder-monitoring-script-using-inotifywait/

In a small script to monitor a folder for new files, the script seems to be finding the wrong files

回答1:

You can use Automator to create a folder action:

Or for example save this plist as ~/Library/LaunchAgents/example.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>example</string>
  <key>ProgramArguments</key>
  <array>
    <string>say</string>
    <string>a</string>
  </array>
  <key>WatchPaths</key>
  <array>
    <string>~/Desktop/</string>
  </array>
</dict>
</plist>

Then run launchctl load ~/Library/LaunchAgents/example.plist to load the plist. To apply changes to the plist, unload and load it. More information:

https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html
https://developer.apple.com/library/mac/technotes/tn2083/_index.html
http://osxnotes.net/launchd.html

A third option is to use Hazel:



回答2:

Save screenshot to ~/screens/

defaults write com.apple.screencapture location ~/screens/
killall SystemUIServer

Save ss2CB.plist to ~/Library/LaunchAgents/

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Disabled</key>
    <false/>
    <key>Label</key>
    <string>copy Screen Shots to ClipBoard</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/python</string>
        <string>~/ss2cb.py</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>~/screens/</string>
    </array>
</dict>
</plist>