Reset Terminal window environments via AppleScript

Mar 28, '03 09:38:00AM

Contributed by: mblakele

I've been building a complicated, brittle system of shell scripts and AppleScript for switching all the little things that "Location Manager" doesn't handle (privoxy's forward settings, stunnel settings, etc.). This hint is about bash settings, and follows the familiar pattern of:


[ -f $HOME/.bash_profile.${LOCATION} ] && \
cp $HOME/.bash_profile.${LOCATION} $HOME/.bash_profile

This sets bash_profile up with my correct environment variables and aliases for each location. That 's fine for new Terminal windows, but what about all those Terminal windows that are already open? Lately I've been finding that what bash can't do, AppleScript can. After the bash_profile has been switched, I run:


tell application "Terminal"
  repeat with w in every window
    -- alt: do script ". $HOME/.bash_profile" in w
    if w is not busy then
      do script "exec bash --login" in w
    end if
  end repeat
end tell

This is a fairly powerful mechanism in general - you could check through the open windows for an idle one, and run a command on it. Look through Terminal's AppleScript dictionary - there's a lot of interesting functionality.

Note that this script seems to have bad interactions with osascript on 10.2.4: I had new windows popping up, for example. Running this AppleScript as a standalone script also avoids the other caveat: the window that you're running osascript in would not, itself, run your shell command. If that's a problem, you could just include the shell command directly in your script - or you could try running osascript in the background.

Comments (3)


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