2

I'm trying to modify some exports. I understand that this code doesn't work because its body executes in a subshell, but how do I fix it?

export | sed 's/gcc.4.2/gcc64/g' | while read line; do $line; done
2
  • Do you want to change the export and then set the environment variable again? If yes then you have to redirect the output to another file and then source the file Commented Jan 12, 2012 at 5:30
  • @Raghuram: Yeah... is there no way to do this from within BASH? Commented Jan 12, 2012 at 5:32

3 Answers 3

5

By arranging for the current shell to read the commands with 'process substitution':

. <(export | sed 's/gcc.4.2/gcc64/g')

Or:

source <(export | sed 's/gcc.4.2/gcc64/g')

(which is more visible, though not as succinct, as the . command).

Sign up to request clarification or add additional context in comments.

2 Comments

+1 although sed -n 's/gcc.4.2/gcc64/gp' would be more efficient.
Only setting that which needs to be set - yes, it would be more efficient. It isn't quite the same as the original, but it is in line with the intent of the original.
2

You can do this without the need for a temp file and I highly discourage the use of eval as you open up your system to all kinds of security problems with it.

while read -r line; do $(sed -n 's/gcc.4.2/gcc64/gp' <<<"$line"); done < <(export)

Also, by using sed -n, this only exports those entries that sed changed.

Comments

1

The file is probably the better solution:

export | sed 's/gcc.4.2/gcc64/g' > ~/tmp/file
. ~/tmp/file

but in case you want to avoid the creation of a temp file

eval $( export | sed 's/gcc.4.2/gcc64/; s/$/;/' )

should do the trick.

1 Comment

This will work with other shells such as Bourne and Korn (give or take the ~ for the Bourne shell). It is probably sub-optimal for bash given the various extra tricks it has up its sleeve, notably process substitution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.