I have tried to make an AppleScript that is supposed to read the current directory from Finder and run a shell command on it. If I navigate to the desired folder in Finder and run the script from AppleScript Editor it works, but when I saved the script and dragged it to the Finder toolbar, currentDir is set to the folder of the script file (my user directory). Here is my script:
tell application "Finder"
set currentDir to POSIX path of ((container of (path to me)) as text)
end tell
tell application "Terminal"
do script "cd " & currentDir
do script "<operation goes here>"
end tell
How can I get the directory active when I use the toolbar shortcut? Second, is there a way to run the shell command in the background, without opening (showing) the Terminal window?
The insertion location
is the folder shown on the title bar of the frontmost Finder window or the desktop.
tell application "Finder" to POSIX path of (insertion location as alias)
Windows have a folder
attribute for the folder shown on the title bar:
tell application "Finder" to POSIX path of ((folder of window 1) as alias)
There's an open bug in 10.7 and 10.8 where both of them (and the selection
property) occasionally refer to older values for them.
This would make the current folder depend on the selection in list view:
tell application "Finder"
if current view of window 1 is in {list view, flow view} and selection is not {} then
set i to item 1 of (get selection)
if class of i is folder then
set p to i
else
set p to container of i
end if
else
set p to folder of window 1
end if
POSIX path of (p as alias)
end tell
Here are two solutions:
1- If the current folder is the target of the front Finder window :
tell application "Finder" to set currentDir to (target of front Finder window) as text
do shell script "cd " & (quoted form of POSIX path of currentDir) & "; <operation goes here>"
--
2 - If the current folder is the selected folder, it will be different in ( list view or coverflow) with respect to the target of the window, because you can select a sufolder in the window (the target of the window will not change) :
tell application "Finder"
set sel to item 1 of (get selection)
if class of sel is folder then
set currentDir to sel as text
else
set currentDir to (container of sel) as text
end if
end tell
do shell script "cd " & (quoted form of POSIX path of currentDir) & "; <operation goes here>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With