Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open iTerm2 from bash script & Run commands

Summary

I'm trying to write a script to automatically launch my development server in iTerm2 from VS Code.

When I open my VS Code project, I want my bash script to:

  1. open iTerm2 (
  2. run cd .. && cd OtherFolder
  3. run npm start (so my node server will start)

Problem

I know how to open iTerm2 but I can't figure out how to make the bash script I wrote then run the commands from #2 and #3 in iTerm2 because I need to run the bash script from the VS Code terminal and then open iTerm2.

like image 303
bzlight Avatar asked Jun 07 '26 06:06

bzlight


2 Answers

My version, based in part on @ubuntudroid's comment:

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
}
like image 94
wytten Avatar answered Jun 10 '26 04:06

wytten


The following bash script uses Applescript to launch iTerm. You can modify it to use iTerm2 instead of 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 $@
like image 30
biozid bostami Avatar answered Jun 10 '26 05:06

biozid bostami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!