你如何打开一个已经cd到特定路径的终端?

时间:2010-08-02 19:00:47

标签: macos terminal applescript

如何使用终端打开另一个终端窗口但是使用我指定的路径?

我上班时使用automator来加载我的工作,但我需要知道如何做到这一点:

打开终端并输入:
•cd工作/公司/项目/
•脚本/服务器

然后在该终端窗口中新建选项卡并cd到同一文件夹。

4 个答案:

答案 0 :(得分:7)

这将从Mac OSX上的命令提示符打开一个新的终端窗口,执行“cd /”然后将窗口保持在最顶层:

osascript -e 'tell application "terminal"' -e 'do script "cd /"' -e 'end tell'

你可以把它放到这样的脚本中:

#!/bin/sh
osascript -e 'tell application "terminal"' -e "do script \"cd $1\"" -e 'end tell'

希望这有帮助。

答案 1 :(得分:2)

使用applescript执行此操作。

e.g。 Open Terminal Here

答案 2 :(得分:0)

您可以编写一个shell脚本来cd到该目录

所以编写一个执行类似cd /user/music之类的东西的脚本,将其另存为myscript.sh并使用chmod +x myscript.sh运行。

来自OS X开发者网络的resource非常有帮助

答案 3 :(得分:0)

下面的两个脚本一起处理常见的场景:

1)如果终端已经在运行,请打开一个新的终端窗口并运行“cd mydir”'有

2)如果终端尚未运行,请使用终端产生的初始窗口(窗口0),而不是烦人地启动第二个窗口

注意:不完美的是,如果终端有多个窗口打开,所有窗口都将被带到前面,与任何其他应用程序重叠。只将最后一个终端窗口提升到前面的解决方案似乎需要AppleScriptObjC的黑魔法 - 参考如下:

https://apple.stackexchange.com/questions/39204/script-to-raise-a-single-window-to-the-front http://tom.scogland.com/blog/2013/06/08/mac-raise-window-by-title/

脚本1 - 打开文本编辑器并另存为:

/usr/local/bin/terminal-here.sh

#!/bin/sh
osascript `dirname $0`/terminal-here.scpt $1 > /dev/null 2> /dev/null

脚本2 - 打开AppleScript编辑器',粘贴下面的内容并另存为:

/usr/local/bin/terminal-here.scpt

# AppleScript to cd (change directory) to a path passed as an argument

# If Terminal.app is running, the script will open a new window and cd to the path
# If Terminal.app is NOT running, we'll use the window that Terminal opens automatically on launch

# Run script with passed arguments (if any)
on run argv
    if (count of argv) > 0 then
        # There was an argument passed so consider it to be the path
        set mypath to item 1 of argv
    else
        # Since no argument was passed, default to the home directory
        set mypath to "~"
    end if
    tell application "System Events"
        if (count (processes whose bundle identifier is "com.apple.Terminal")) is 0 then
            # Terminal isn't running so we'll make sure to run the 'cd' in Terminal's first window (0)
            tell application "/Applications/Utilities/Terminal.app"
                # Turn off echo, run the 'cd', clear screen, empty the scrollback, re-enable echo
                do script "stty -echo; cd " & (mypath as text) & ";clear; printf \"\\e[3J\"; stty echo" in window 0
                activate last window
            end tell
        else
            # Terminal is already running so we'll let it open a new window for our 'cd' command
            tell application "/Applications/Utilities/Terminal.app"
                # Turn off echo, run the 'cd', clear screen, empty the scrollback, re-enable echo
                do script "stty -echo; cd " & (mypath as text) & ";clear; printf \"\\e[3J\"; stty echo"
                activate last window
            end tell
        end if
    end tell
end run