I am writing a bash script in which a small python script is embedded. I want to pass a variable from python to bash. After several searches, I found a method based on os.environ.
I just can't get it to work. Here is my simple test.
#!/bin/bash
export myvar='first'
python - <<EOF
import os
os.environ["myvar"] = "second"
EOF
echo $myvar
I expected it to output second, however it still displays first. What happened to my script? Also is there a way to pass a variable without export?
Summary
Thanks for all the answers. Here is my resume.
The Python script built into bash will be executed as a child process, which by definition cannot affect the parent environment of bash.
The solution is to pass destination strings from python and evalsubsequently to bash.
An example is
#!/bin/bash
a=0
b=0
assignment_string=$(python -<<EOF
var1=1
var2=2
print('a={};b={}'.format(var1,var2))
EOF
)
eval $assignment_string
echo $a
echo $b