2

I am looking for a way to automatically open a new window of Terminal.app and run a command in it.

I used to do this with AppleScript, in a way similar to this:

tell application "Terminal"
  do script ("some-command")
end tell

The official distribution of Julia opens terminal windows in the same way.

However, if Terminal.app is set up to run a command on startup (which is an often recommended practical way to set a new shell without changing the login shell globally), this method simply fails.

Is there a robust method that works even when an alternative shell is used?

enter image description here

  • Why wouldn’t you change your log in shell, rather than use the command overload? I believe my answer should work either way, so I’ll assume you have some good reason to choose this. – bmike Jun 15 at 21:18
  • @bmike I used this method because it was recommended by MacPorts: trac.macports.org/wiki/howto/bash-completion I was wary of changing the login shell to something that may be removed or break (e.g. a failed upgrade). I don't know what would happen then. – Szabolcs Jun 16 at 8:29
2

Save whatever script you wish to a file and when you change the extension to .command

Finder will robustly make a command line window that’s new to run that command / script. This works for whatever #!/bin/whatever shell or script you start the text file.

AppleScript can open documents just like when Finder clicks on them to open, this should be a fairly universal way to accomplish your task.

  • The file also has to be made executed, otherwise one will get the error e.g.: "The file “filename.command” could not be executed because you do not have appropriate access privileges." – user3439894 Jun 15 at 23:12
  • @user3439894 Indeed. I should probably expand this a little with another edit – bmike Jun 15 at 23:28
  • One missing piece was: to launch this .command file programmatically, one must use open. However, it still doesn't work if Terminal is set to run a command on startup. It suffers from the same issue as the AppleScript method I used before. Does it work for you? – Szabolcs Jun 16 at 8:33
  • 1
    Actually, it seems that the problem appears only when I set Terminal to use MacPorts's bash (/opt/local/bin/bash) or MacPorts's zsh. If I set it to use something else, e.g. /bin/zsh or /bin/ksh, then everything works fine, even with the AppleScript solution. – Szabolcs Jun 16 at 8:38
  • Huzzah @Szabolcs - I’ve been on iOS away from macOS all weekend. I welcome a substantial edit to my answer or your making a clearer answer and selecting it if you prefer. – bmike Jun 16 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .