views:

51

answers:

2

I would like to be able to source a file to set up some environment variables, but do it so it's independent of the shell being used.

For example

%: source START.env

# START.env
if [ $SHELL == "bash" ]; then
  source START.env.bash  # sets environment variables
else
  source START.env.tcsh  # sets environment variables
fi

However, this code will only work for bash. How can one make it compatible with both bash and tcsh?

I have to source the file because I want the environment variables to stick afterwards.

A: 

Create your variable file for tcsh:

setenv FOO 42
setenv BAR baz
setenv BAZ "foo bar"

In your tcsh script use:

source filename

In your Bash script use:

while read -r cmd var val
do
    if [[ $cmd == "setenv" ]]
    then
        declare -x "$var=$val"
    fi
done < filename

It would be somewhat difficult to create a script that would run on both tcsh and Bash.

Dennis Williamson
A: 

You could do what Dennis says. Or I think this is slightly more eloquent

(in bash)

sed -i 's/setenv \([a-zA-Z0-9_]*\) /declare -x \1=/g' filename
source filename

(in tcsh script)

sed -i 's/declare -x \([a-zA-Z0-9_]*\)=/setenv \1 /g' filename
source filename

(Note this will actually change your sourced file to the appropriate syntax each time it's run.)

Jason R. Mick