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

后端 未结 6 727
夕颜
夕颜 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:22

    The answer from @david-moles above works but run the terminal and command in ~ rather the current working directory where term was launched. This variation adds a cd command.

    #!/usr/bin/env bash
    # based on answer by @david-moles in 
    # https://stackoverflow.com/questions/4404242/programmatically-launch-terminal-app-with-a-specified-command-and-custom-colors
    echo "
    on run argv
      if length of argv is equal to 0
        set command to \"\"
      else
        set command to item 1 of argv
      end if
      set command to \"cd '"$PWD"' ;\" & command
      if length of argv is greater than 1
        set profile to item 2 of argv
        runWithProfile(command, profile)
      else
        runSimple(command)
      end if
    end run
    
    on runSimple(command)
      tell application \"Terminal\"
        activate
        set newTab to do script(command)
      end tell
      return newTab
    end runSimple
    
    on runWithProfile(command, profile)
      set newTab to runSimple(command)
      tell application \"Terminal\" to set current settings of newTab to (first settings set whose name is profile)
    end runWithProfile
    " | osascript - "$@" > /dev/null
    

    There may be a way to set PWD this with applescript.

    Note: When I use this, I sometimes two Terminal windows, one a shell running in ~ and a second which runs the cd command and command from argv[1]. Seems to happen if Terminal is not already running; perhaps it is opening old state (even tho I had no open terminals when I closed it).

提交回复
热议问题