user541686
user541686

Reputation: 210781

Export from piped while loop in Bash?

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

Upvotes: 2

Views: 1269

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 755114

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).

Upvotes: 5

SiegeX
SiegeX

Reputation: 140567

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.

Upvotes: 2

Diego Torres Milano
Diego Torres Milano

Reputation: 69426

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.

Upvotes: 1

Related Questions