Jump to content

A bash script to get path of document open by the frontmost window


Recommended Posts

filename=$(echo 'tell application "System Events"
  set theprocess to the first process whose frontmost is true
  set thetitle to the value of the attribute "AXTitle" of theprocess
  set thewindow to the value of attribute "AXFocusedWindow" of theprocess  
  set thefile to the value of attribute "AXDocument" of thewindow as string
  if thetitle is "Finder" then
      tell application "Finder"
         set thefile to (POSIX path of (target of the first window as alias))
      end tell
  end if
  set thefile to thefile
end tell' | osascript -ss | php -r 'echo urldecode(fgets(STDIN));')
filename=${filename%\"}
filename=${filename#\"}
filename=${filename#file://localhost}
dirname=$(dirname "$filename")
basename=$(basename "$filename")

 

hope this is useful for you

Link to comment

Nice script. Just want to point out that you need "Enable access for assistive devices" checked in the Accessibility preference pane for this to work.

 

Generally, it'll work with apps that display a little document icon in the menu bar. It should work fine in text editors like Sublime Text or TextMate, but I've had trouble getting the proper AXDocument in Xcode -- not sure if there's a way around that in AppleScript.

 

It might also be useful to get the selection in Finder rather than the open folder, but you'd have to figure out a way to deal with multiple selected files.

 

Edit: Oh, and if you wanted to turn this into a workflow, you could just add something like `tell app "Alfred 2" to search "$filename"` to view the file in Alfred.

Edited by Clinton Strong
Link to comment
  • 2 weeks later...
  • 7 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...