通过Automator可以自意义services,services可以认为是扩展菜单,为应用添加系统未曾提供的功能。本文通过Automator为Finder添加一个扩展菜单,实现当在Finder中选中一个文件夹时,可通过右键菜单直接打开iTerm,并定位到对应目录下。
添加Service
新建一个Automator,类型选择Service。
添加两个Action,第一个为Get Selected Finder Items,这个是第二个Action的输入参数,当用鼠标选中文件时,通过这个Action可以获得文件夹路径等信息。
第二个Action为Run AppleScript,Action如下图所示:
在第二个Action中添加AppleScript,这样当执行service时,便会触发AppleScript执行,AppleScript如下:
-- Adapted from these sources:
-- http://peterdowns.com/posts/open-iterm-finder-service.html
-- https://gist.github.com/cowboy/905546
--
-- Modified to work with files as well, cd-ing to their container folder
on run {input, parameters}
tell application "Finder"
set my_file to first item of input
set filetype to (kind of (info for my_file))
-- Treats OS X applications as files. To treat them as folders, integrate this SO answer:
-- http://stackoverflow.com/a/6881524/640517
if filetype is "Folder" or filetype is "Volume" then
set dir_path to quoted form of (POSIX path of my_file)
else
set dir_path to quoted form of (POSIX path of (container of my_file as string))
end if
end tell
CD_to(dir_path)
end run
on CD_to(theDir)
tell application "iTerm"
activate
set go_dir to "cd " & theDir
set newWindow to (create window with default profile)
tell current session of first window
write text go_dir
end tell
end tell
end CD_to
完成上述步骤后,保存Service,命名为:Open iTerm Here。
测试Service
打开Finder,随便选中一个文件夹,然后右击,选择services -> Open iTerm Here,一切顺利的话,可正确打开iTerm。