Mark Harrison
Mark Harrison

Reputation: 304494

How do I execute a command in an iTerm window from the command line?

How do I run an iTerm session from the command line, passing in the command which is to be executed in the iTerm window?

The xterm analog is -e, i.e.

xterm -e sleep 10

Upvotes: 14

Views: 19318

Answers (3)

SamG
SamG

Reputation: 171

I had found the official documentation, but hadn't thought to wrap the Applescript up with osascript like SushiHangover- very nice. His answer didn't work for me, probably because I'm using the latest beta 3.0 version, so here's one that does work (and also simplifies a bit).

#!/bin/bash
osascript - "$@" <<EOF
on run argv
tell application "iTerm"
    activate
    set new_term to (create window with default profile)
    tell new_term
        tell the current session
            repeat with arg in argv
               write text arg
            end repeat
        end tell
    end tell
end tell
end run
EOF

Upvotes: 17

SushiHangover
SushiHangover

Reputation: 74164

I agree with Alex, using the AppleScript the best way to go.

Here is my "iterm" script that I chmod as executable and have it in a directory that is in my path. I can use it like this:

Quote enclosed shell arguments:

iterm "ls -l" 

Pass multiple cmds to run:

iterm "calculatesomthing" "exit"

Pass multiple cmds, semicolon separtated:

iterm "cd ~/mediaprojects; ./gitSyncAll; exit" 

The self enclosed bash/Applescript:

#!/bin/bash
read -r -d '' script <<'EOF'
on run argv
tell application "iTerm"
    activate
    set myterm to (make new terminal)
    tell myterm
        launch session "Default"
        tell the last session
            repeat with arg in argv
               say arg
               write text arg
            end repeat
        end tell
    end tell
end tell
end run
EOF
echo "$script" | osascript ``-'' $@

FYI: You might want to remove the "say" command, I use it as a remote/audible notification of each cmd being executed. I pass a bunch of cmds to multiple custom iTerm profiles/shell that gets tiled to a large flat screen to show the status of an complex multi-DC Azure deployment...

PS: I added a gist as the quotes in the last line of the script were not cut/pasting properly for someone @ https://gist.github.com/sushihangover/7563e1707e98cdf2b285

Upvotes: 9

alexgolec
alexgolec

Reputation: 28252

You're best off using Applescript for this. iTerm2 has some examples of scripts. The documentation is a little shoddy, but those examples should give you an idea of where to start.

You can wrap the Applescript string in a bash script and then launch it using osascript:

#~/bin/bash
tell application "iTerm"
    # etc...
    exec command "$@"

Then running the script is as simple as:

./run-in-iterm.sh "echo 'hello world'"

Upvotes: 5

Related Questions