从 bash 脚本打开 iTerm2 并运行命令

问题描述 投票:0回答:3

总结

我正在尝试编写一个脚本来从 VS Code 自动启动 iTerm2 中的开发服务器。

当我打开 VS Code 项目时,我希望 bash 脚本能够:

  1. 打开 iTerm2 (
  2. 运行 cd .. && cd 其他文件夹
  3. 运行 npm start (这样我的节点服务器就会启动)

问题

我知道如何打开 iTerm2,但我不知道如何制作我编写的 bash 脚本,然后在 iTerm2 中运行 #2 和 #3 中的命令,因为我需要从 VS Code 终端运行 bash 脚本,然后打开iTerm2.

linux bash unix scripting
3个回答
2
投票

以下 bash 脚本使用 Applescript 启动 iTerm。您可以修改它以使用 iTerm2 而不是 iTerm。

#!/bin/bash
#
# Open new iTerm window from the command line
#
# Usage:
#     iterm                   Opens the current directory in a new iTerm window
#     iterm [PATH]            Open PATH in a new iTerm window
#     iterm [CMD]             Open a new iTerm window and execute CMD
#     iterm [PATH] [CMD] ...  You can prob'ly guess
#
# Example:
#     iterm ~/Code/HelloWorld ./setup.sh
#
# References:
#     iTerm AppleScript Examples:
#     https://gitlab.com/gnachman/iterm2/wikis/Applescript
# 
# Credit:
#     Inspired by tab.bash by @bobthecow
#     link: https://gist.github.com/bobthecow/757788
#

# OSX only
[ `uname -s` != "Darwin" ] && return

function iterm () {
    local cmd=""
    local wd="$PWD"
    local args="$@"

    if [ -d "$1" ]; then
        wd="$1"
        args="${@:2}"
    fi

    if [ -n "$args" ]; then
        # echo $args
        cmd="; $args"
    fi

    osascript &>/dev/null <<EOF
        tell application "iTerm"
            activate
            set term to (make new terminal)
            tell term
                launch session "Default Session"
                tell the last session
                    delay 1
                    write text "cd $wd$cmd"
                end
            end
        end tell
EOF
}
iterm $@

1
投票

这个小程序是我为自己构建的,可以满足您的需求。它需要一个像这样的配置文件:

{
  "tabs": [
    {
      "commands": ["cd /to/other/folder", "cd /to/project && npm start"]
    }
  ]
}

0
投票

我的版本,部分基于@ubuntudroid的评论:

function dovt
{
    osascript <<EOF
    tell application "iTerm2"
         create window with default profile
         tell current session of current window
              delay 1
              write text "cd $PWD"
              write text "$@"
          end tell
    end tell
EOF
}
© www.soinside.com 2019 - 2024. All rights reserved.