Applescript 在当前空间打开一个新的终端窗口

zaf*_*zaf 16 terminal applescript osx-snow-leopard

是的,我对 Apple Script 的新手体验很糟糕。

我需要在当前桌面空间中打开一个新的终端窗口。不要将我移动到另一个运行终端的空间,然后打开另一个终端窗口。

当然,如果终端没有运行,那么它应该启动一个新的终端进程。

Jus*_*kva 18

tell application "Terminal"  
    do script " "  
    activate  
end tell
Run Code Online (Sandbox Code Playgroud)

这看起来很奇怪,但它利用了终端如何处理传入的“执行脚本”命令的奇怪之处;它为每个人创建一个新窗口。如果你愿意,你实际上可以用一些有用的东西来代替它;打开新窗口后,它会执行您想要的任何操作。


Ada*_*dam 16

如果在 do 脚本 " " 之间没有任何文本,您将不会在终端中获得额外的命令提示符。

tell application "Terminal"  
    do script ""  
    activate  
end tell
Run Code Online (Sandbox Code Playgroud)


小智 10

我可以想到三种不同的方法来做到这一点(前两种是从别处偷来的,但我忘记了在哪里)。我使用第三个,它从applescript 调用shell 脚本,因为我想每次都打开一个新窗口,而且它是最短的。

与至少从 10.10 起内置于 OS X 中的脚本不同,所有这些都在查找器窗口中当前工作目录的任何目录中打开终端(即,您不必选择文件夹即可打开它)。

还包括几个 bash 函数来完成 Finder > Terminal > Finder 圆圈。

1. 重用现有选项卡或创建一个新的终端窗口:

tell application "Finder" to set myDir to POSIX path of (insertion location as alias)
tell application "Terminal"
    if (exists window 1) and not busy of window 1 then
        do script "cd " & quoted form of myDir in window 1
    else
        do script "cd " & quoted form of myDir
    end if
    activate
end tell
Run Code Online (Sandbox Code Playgroud)

2. 重用现有选项卡或创建新的终端选项卡:

tell application "Finder" to set myDir to POSIX path of (insertion location as alias)
tell application "Terminal"
    if not (exists window 1) then reopen
        activate
    if busy of window 1 then
        tell application "System Events" to keystroke "t" using command down
    end if
    do script "cd " & quoted form of myDir in window 1
end tell
Run Code Online (Sandbox Code Playgroud)

3.每次通过从applescript调用的shell脚本生成一个新窗口

tell application "Finder"
    set myDir to POSIX path of (insertion location as alias)
    do shell script "open -a \"Terminal\" " & quoted form of myDir
end tell
Run Code Online (Sandbox Code Playgroud)

4. (BONUS) Bash 别名为终端中的当前工作目录打开一个新的查找窗口

将此别名添加到您的 .bash_profile。

alias f='open -a Finder ./' 
Run Code Online (Sandbox Code Playgroud)

5.(奖励)将终端窗口中的目录更改为前 Finder 窗口的路径

将此函数添加到您的 .bash_profile。

cdf() {
      target=`osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)'`
        if [ "$target" != "" ]; then
            cd "$target"; pwd
        else
            echo 'No Finder window found' >&2
        fi
}
Run Code Online (Sandbox Code Playgroud)