Programmatically launch Terminal.app with a specified command (and custom colors)

后端 未结 6 720
夕颜
夕颜 2020-12-08 01:03

I can launch an xterm from the command line (or a program, via a system call) like so:

/usr/X11/bin/xterm -fg SkyBlue -bg black -e myscript

6条回答
  •  清歌不尽
    2020-12-08 01:31

    Almost all (every?) osx program can be launched from command line using:

    appName.app/Contents/MacOS/command

    For terminal the command is:

    /Applications/Utilities/Terminal.app/Contents/MacOS/Terminal

    You can use the autocomplete (tab) or ls to find the correct filenames. ".app" is basically a folder.

    To change the colors and run a script... I think you cannot do it with shell scripts as Terminal does not accept arguments ("Terminal myScript.sh" does not launch myScript). With iTerm this works.

    Workaround is to use applescript (wrapped in a shell script):

       #!/bin/sh
       osascript -e '
         tell application "Terminal"
           activate
           tell window 1
              do script "sleep 5; exit"
              set background color to {0, 11111, 11111}
              set win_id to id
           end tell
    
           set w_ids to (id of every window)
    
           repeat while w_ids contains win_id
             delay 1
             set w_ids to (id of every window)
           end repeat
        end tell'
    

    Ok, now it should behave exactly the same as the xterm example. The drawback is the constant polling of the window ids (which is bad programming).

    edit: A bit more elegant applescript would use the 'busy' property of Terminal. I will leave the original code as is works for a general program (not just terminal).

    tell application "Terminal"
        tell window 1
            do script "sleep 2"
            set background color to {0, 11111, 11111}
            repeat while busy
                delay 1
            end repeat
            close
        end tell
    end tell
    

    Also for perfectly correct program, one should check that whether the terminal is running or not. It affects the number of windows opened. So, this should be run first (again a nasty looking hack, that I will edit later as I find a working solution).

    tell application "System Events"
        if (count (processes whose name is "Terminal")) is 0 then
            tell application "Terminal"
                tell window 1
                    close
                end tell
            end tell
        end if
    end tell
    

    br,
    Juha

提交回复
热议问题