使用Mac的用户有时候会遇到需要当前目录下打开Terminal的情况,例如需要对某一级目录下的文件进行授权、执行等操作,一般的做法是先复制该目录的路径,然后打开Terminal,最后在Terminal中执行cd命令,网上也有一些办法可以在Finder工具栏添加打开Terminal的方式,但是操作起来都不是很方便,因此特地开发出该Alfredworkflow,目前已能实现在任意目录一键打开Terminal并自动执行cd 命令,基本原理就是利用AppleScript获取到当前文件/文件夹所在的Finder目录,唤醒Terminal或者iTerm并执行cd命令。
2、准备工作
脚本为Alfredworkflow,使用者需要自行进行安装Alfred,安装后直接导入即可。
3、脚本介绍
3.1、iTerm脚本
on alfred_script(q)tell application "Finder"set pathFile to selection as textif pathFile is "" then set pathFile to (path to desktop folder from user domain)set pathFile to get POSIX path of pathFile--防止目录存在空格跳转不了set pathFile to quoted form of pathFileset realPath to pathFileif pathFile is "/" then return realPath--如果是文件夹路径直接返回if pathFile ends with "/" then set pathFile to (characters 1 thru -2 of pathFile) as string--分割set tid to AppleScript's text item delimitersset AppleScript's text item delimiters to "/"set allComponents to every text item of pathFileset AppleScript's text item delimiters to ""--判断是否为空目录if (count allComponents) is 1 then set realPath to ""set allComponents to (items 1 thru -2) of allComponentsset AppleScript's text item delimiters to "/"set newPath to allComponents as textset AppleScript's text item delimiters to ""if newPath does not end with "/" then set newPath to (newPath & "/") as stringset AppleScript's text item delimiters to tidset realPath to newPathset realPath to "cd " & realPath & "'"log realPath--set the clipboard to pathFile--set realPath to realPath & "'"--set the clipboard to pathFiletell application "iTerm"create window with default profiletell current session of current windowwrite text realPathend tellend tellend tellend alfred_script
3.2、Terminal脚本
on alfred_script(q)tell application "Finder"set pathFile to selection as textif pathFile is "" then set pathFile to (path to desktop folder from user domain)set pathFile to get POSIX path of pathFile--防止目录存在空格跳转不了set pathFile to quoted form of pathFileset realPath to pathFileif pathFile is "/" then return realPath--如果是文件夹路径直接返回if pathFile ends with "/" then set pathFile to (characters 1 thru -2 of pathFile) as string--分割set tid to AppleScript's text item delimitersset AppleScript's text item delimiters to "/"set allComponents to every text item of pathFileset AppleScript's text item delimiters to ""--判断是否为空目录if (count allComponents) is 1 then set realPath to ""set allComponents to (items 1 thru -2) of allComponentsset AppleScript's text item delimiters to "/"set newPath to allComponents as textset AppleScript's text item delimiters to ""if newPath does not end with "/" then set newPath to (newPath & "/") as stringset AppleScript's text item delimiters to tidset realPath to newPathset realPath to "cd " & realPathlog realPath--set the clipboard to pathFileset realPath to realPath & "'"tell application "Terminal"do script (realPath)activateend tellend tellend alfred_script
4、总结
目前该项目在GitHub,有需要的可以移步我的博客http://codersoft.gitee.io 或者点击阅读原文进行查看、下载脚本,感谢您的关注!