I am having trouble exporting environmental variables from stdout.
What do I do wrong and how to fix it?
$ cat env.py
print("export TEST_ME=123")
$ python env.py
export TEST_ME=123
$ echo $(python env.py)
export TEST_ME=123
$ echo $(python env.py) | . /dev/fd/0
bash: echo: write error: Broken pipe
$ echo "export TEST_ME=123" | . /dev/fd/0 && echo $TEST_ME
$
Same command works in zsh
$ zsh
% echo "export TEST_ME=123" | . /dev/fd/0 && echo $TEST_ME
123
%
Update:
Python3.9 on macOS gets that broken pipe, so I am trying with just echo
$ bash --noprofile --norc
bash-3.2$ . <(echo "export TEST_ME=123") && echo $TEST_ME
bash-3.2$ . <(python3.9 env.py)
bash-3.2$ Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
BrokenPipeError: [Errno 32] Broken pipe
bash-3.2$ . <(python2 env.py)
bash-3.2$ close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
bash-3.2$
CodePudding user response:
Use process substitution:
$ . <(python env.py)
$ echo $TEST_ME
123
The way this works is: it creates a temporary pipe in the filesystem, and connects stdout of python env.py
to the pipe. The <(...)
construct itself is then replaced by the file name of that pipe.