4

I am using MSYS and have a file vars.txt with variable, value keys like:

WINDIR C:/WINDOWS
STS_BUILD_DIRECTORY D:/STS/TMP
ALLUSERSPROFILE C:/Documents and Settings/All Users

I want to read this in and set environment variables up. I have a bash script setenv:

while read var value;
do
  echo "performing export $var=$value"
  export $var='$value'
done 

and I call it with

cat vars.txt | source setenv

However in my environment the variables are not set. I also tried making it into a function but no joy. Anybody here know what I'm doign wrong? Thanks.

3
  • 1
    setenv is a poor name for your script, since it's the name of a builtin in several shells.
    – Daenyth
    Commented Sep 17, 2010 at 18:43
  • @Daenyth Thanks - yeah it felt kind of wrong at the time but bash doesn't seem to have it. mapenv is a better name anyways ;)
    – danio
    Commented Sep 20, 2010 at 8:30
  • I have also found same issue(vars not set) if I add a pipe after sourcing a script. e.g. 'source setit.sh' vars set ok, 'source setit.sh |tee setit.log' vars are not set. Surprising. Not intuitive. Watch out.
    – gaoithe
    Commented Sep 8, 2016 at 11:53

1 Answer 1

7

The pipe sets up a subshell. When the subshell exits, the variables are lost.

Try this:

source setenv < vars.txt

Also your single quotes may prevent the expansion of the variable (I don't know if this is true in MSYS). Try changing the export line to this:

export $var="$value"

You can use declare instead of export if the variables don't need to be exported.

5
  • So I have to use temp files? (vars.txt was just for testing) I have a function that generates vars.txt. It works OK with: generate_envmap > /tmp/envmap.txt; apply_env < /tmp/envmap.txt. Would be nicer to do generate_envmap | apply_env.
    – danio
    Commented Sep 20, 2010 at 8:50
  • 2
    @danio: I just based my answer on your example. You said you "have a file". I didn't know that you didn't already have the file. You can use process substitution in Bash: source apply_env < <(generate_envmap) Commented Sep 20, 2010 at 13:14
  • Thanks that seems to be what I want but the MSYS version of bash doesn't seem to have implemented process substitution :-(
    – danio
    Commented Sep 21, 2010 at 8:21
  • @danio: Try using a here string and command substitution: source apply_env <<< $(generate_envmap) Commented Sep 21, 2010 at 10:12
  • Thanks for that but doesn't seem to do anything. No errors, but no effect either. The temp file solution is a little ugly but fine.
    – danio
    Commented Sep 21, 2010 at 11:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .