Create customized new terminal windows

Dec 23, '01 10:23:45AM

Contributed by: Anonymous

Since I installed OS X, I've wanted to be able to pop up Terminal windows that have a specified title and are running a specified application. I'm about 90% there, and thought I'd share what I've written with the MacOSXhints gang.

Note that this is a Unix shell script that you'll want to copy onto your system, save with some name ('newterm'), then use chmod +x newterm or similar to ensure that it's executable.

Then you can start up a new Terminal window with the title "my terminal" and the core shell of /usr/bin/vi (for example), with:

newterm "Edit Window" "/usr/bin/vi"
Pretty cool, eh?

Read the rest of the article for the "new term" shell script.

#!/bin/sh

# NEWTERM - launch a new Terminal.app window with the specified
# command as the default to execute upon launch. This
# also changes the TITLE of the window to be the command
# or the specified title if that parameter is specified.
#
# Released into the Public Domain by Dave Taylor (taylor@intuitive.com)

termname="com.apple.Terminal"
terminal="/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"

# step zero: do we have meaningful starting parameters?

if [ $# -ne 2 ] ; then
echo "Usage: `basename $0`: title app"
exit 0
fi

newtitle="$1"
newshell="$2"

if [ "$newshell" = "" ] ; then
newshell='""' # make sure that there's a no-value string value!
fi

# step one, let's get and save the existing Terminal.app configuration

oldtitle="`defaults read $termname | grep CustomTitle | cut -d= -f2 | sed 's/; //;s/^ //'`"
oldshell="`defaults read $termname | grep 'Shell ' | cut -d= -f2 | sed 's/; //;s/^ //'`"

# step two: change the settings temporarily

defaults write $termname CustomTitle "$newtitle"
defaults write $termname Shell "$newshell"

# and launch the new Terminal as requested by the user

$terminal &

# step three: reset the values to their defaults
# but, we need to leave them intact while the Terminal app
# actually starts up, so we'll drop the reset into a background
# subshell and have it sleep for 5 seconds before resetting.
# * Note that this means you should NOT run multiple NEWTERM
# * processes without at least a 5 second pause between them

(
sleep 5
defaults write $termname CustomTitle "$oldtitle"
defaults write $termname Shell $oldshell
) &

# and we're done. Way cool.

exit 0
I've been trying to get it to work so that you can specify an arbitrary command (for example "vi test.c") but that requires creating a temporary startup script and pointing Terminal to that script, which works fine except I don't like how it exits. Stay tuned, though, I'll crack this code yet! [of course, documentation would be nice!]

Comments (3)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20011223102345128