osascript 打开termainal新页

How to programmatically open a new terminal tab or window

I stumbled across this while trying to calculate some configuration options and open multiple terminal windows at once to run multiple Node services.

There are two ways to programmatically open a new terminal window or tab on a mac, depending on whether or not you use iTerm or the default Terminal program. I’ll share both, with a brief explanation on how it works.

 

Open a new window in iTerm2

osascript -e "
      tell application \"iTerm2\"
        set newWindow to (create window with default profile)
        tell current session of newWindow
            write text \"env \"
        end tell
      end tell
    "
Bash

Open a new tab in iTerm2

osascript -e "
      tell application \"iTerm2\"
        set newTab to (create tab with default profile)
        tell current session of newTab
            write text \"env \"
        end tell
      end tell
    "
Bash

Open a new window in Terminal

osascript -e "
      tell application \"Terminal\"
        activate
        tell application \"System Events\" to keystroke \"t\" using command down
        repeat while contents of selected tab of window 1 starts with linefeed
          delay 0.01
        end repeat
        do script \"env\" in window 1
      end tell
    "
Bash

`osascript` is a command to run AppleScript. They can be enclosed in a string or in a file. The `-e` flag tells it that you are passing a command as a string. The weird rules with shell string escaping make it a little challenging to do anything too complicated with this passed in command. There are many more options you can explore with `man osascript`.

Pass arguments to AppleScript file

One final interesting tip. You can save avoid the quote mess with the `-e` flag by saving your AppleScript in a separate file and passing in an argument:

osascript pathToYourScript.scpt myargument
Bash

Then in the AppleScript file itself you can access the arguments with a `item 1 of argv` syntax like so:

on run argv
    tell application "Terminal"
        do script "./myscanprogram " & (item 1 of argv) & " 2>&1"
    end tell
end run
Bash

I don’t know a whole lot about AppleScript but have heard it can automate just about anything related to your mac. Perhaps I’ll dedicate a future blog post to some interesting use for this.

上一篇:Mac技巧|如何用键盘快捷键打开 macOS 控制中心


下一篇:Python基础教程——for循环语句