Issue
I have a script test.sh
:
#!/bin/bash
export VAR1=abc123
echo $VAR1
I want the variable set in test.sh
to be set in the shell from which I run this script, so I use source
:
$ source test.sh
abc123
$ echo $VAR1
abc123
But let's say I want to do something with the output of test.sh
. It seems that if I pipe the output of test.sh
, sourcing the variable no longer works:
$ VAR1=xyz
$ source test.sh | sed 's/abc/xyz/g'
xyz123
$ echo $VAR1
xyz
As opposed to the expected:
$ VAR1=xyz
$ source test.sh | sed 's/abc/xyz/g'
xyz123
$ echo $VAR1
abc123
How can I get around this if I want to set a variable and modify the output using one script?
Solution
When you run :
source test.sh | sed 's/abc/xyz/g'
source test.sh
is run in a subshell so has no effect on the parent shell.
You need process substitution :
source test.sh > >(sed 's/abc/xyz/g')
Answered By - Philippe Answer Checked By - Pedro (WPSolving Volunteer)