Terminal.app equivalent of `xterm -e 'cmd'`

With xterm (and gnome-terminal, terminator, etc), you can run the following command:

$ xterm -e 'vim somefile.txt'

xterm will open and run the specified program (in this case, Vim). When the program exits, the terminal window closes as well. Running the above command, if you were to quit Vim, the terminal would go away as well.

Is there any way to get this (or similar) functionality through Terminal.app (on OSX)? The solution can be in AppleScript, Bash or anything else really, as long as it's achievable via commands I could run in a Bash script.


Solution 1:

With AppleScript, you can do:

on run argv
    set command to item 1 of argv --you can customize this to be constant
    tell application "Terminal"
        activate
        do script (command & "; exit")
    end tell
end run

This will open Terminal and tell it to run a command (Your default settings need to close the window when the shell exits). To run this, just use osascript filename.scpt "$command_to_run"

Solution 2:

You could use the open command (/usr/bin/open).

For example, say that I want to open the file test.txt with Textmate and close the shell afterwards. I could use the following command:

open -W -a Textmate test.txt && exit
  • The -W option will cause it to wait until Textmate is closed.
  • The -A option allows you to specify the application

The second part of the command line (exit) will not cause the Terminal application to quit, but can close the Terminal window if you change the default preferences. In the Terminal preferences, click on the Shell tab and change the setting When the shell exits to Close the window

Terminal preferences

If you really want to exit the Terminal application, you could replace exit by a call to a Bash script. For example:

#!/bin/sh

echo | osascript <<EOF
tell application "Terminal"
  quit
end tell
EOF

(Source adapted from Mac OS X Hints)

This will still cause Terminal to show a popup asking if you want to close the application.

Terminal popup