Populate tcsh environment variables via a script

Apr 01, '04 10:48:00AM

Contributed by: ssantry

I have a G4 Cube (running Panther) that I use for serving web pages, hosting a CVS repository and for a few other things. Fairly often I need to log into this machine over SSH to perform some remote administration.

The problem is I followed this tip from Apple to load environment variables (like CVSROOT and CVS_RSH) into the GUI environment using ~/.MacOSX/environment.plist. So, if I log in remotely using SSH, those environment variables aren't set in my shell environment. While I could just duplicate the setting of these environment variables in ~/.tcshrc (or ~/Library/init/tcsh/environment.mine if you followed this hint), as a programmer I know that duplication of data is the root of all evil :-).

I've wanted to learn Ruby, so I decided to whip together a little script to parse ~/.MacOSX/environment.plist and load the variables into the tcsh environment. Save this script in a file called parseEnvironmentPlist.rb in your ~/bin directory:

#!/usr/bin/ruby

#
# A script for parsing ~/.MacOSX/environment.plist and loading the 
# environment variables it defines into a tcsh environment.
#

# a regex for matching <key>...</key> lines
# group 1 is the name of the key
key_re = /^\s*<key>([A-Za-z]+[_A-Za-z0-9]*)<\/key>\s*$/

# a regex for matching <string>...</string> value lines
# group 1 is the value of the environment variable
value_re = /^\s*<string>([-_:.\/0-9A-Za-z]+)<\/string>\s*$/

File.open("#{ENV['HOME']}/.MacOSX/environment.plist", "r") do |plist|

 currentKey = "" # the key we're currently processing
 
 # look at each line of the file to find keys
 # followed by values
 plist.each_line do |next_line| 
  
  # if we find a key, hold on to it 
  if key_re =~ next_line
   currentKey = $1
   currentValue = ""
  
  # since key lines alternate with value lines,
  # if we match a value line, we know it's a value
  # for the previously matched key
  elsif value_re =~ next_line
   currentValue = $1
   
   # output a setenv command to stdout that's 
   # suitable for running through tcsh's eval
   puts "setenv #{currentKey} #{currentValue};"
   
   currentKey = currentValue = ""
  end
  
 end

end
Make the script executable (execute chmod 750 ~/bin/parseEnvironmentPlist.rb in Terminal) and add the following line to your ~/.tcshrc (or ~/Library/init/tcsh/rc.mine if you've followed this hint):
eval `~/bin/parseEnvironmentPlist.rb`
Note that those are backticks in the above command, NOT single quotes! Now you can keep all your environment variable definitions in a single location (~/.MacOSX/environment.plist) and still use them when you log in remotely!

Comments (10)


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