According to voithos's answer, os.environ
can set environment variables and subprocess automatically inherit from parent process.
However, compare below to cases
First case, in python interaction mode
>>>import os
>>>os.environ['a']='1'
>>>os.system('echo $a')
1
0
The result is fine.
Second case, in bash script
#!/bin/bash
python3 - <<EOF
import os
os.environ['a']='1'
os.system('echo $a')
EOF
save the above as test.bash
and run bash test.bash
we got nothing!
Why in the second case, os.system
doesn't inherit variable?
summary
Any dollar sign $
in bash here document will be expanded by default, no matter it is inside single quotes or not.
One way is to escape $
with backslash \
like \$
There is another way to avoid this expand, that is to single quote the first here doc delimiter, compare following
a=0
python3 - <<here
import os
os.environ['a']='1'
os.system('echo $a')
here
python3 - <<'here'
import os
os.environ['a']='1'
os.system('echo $a')
here