Bash – Pass bash variable into python file

bashlinuxpython

I have a Python script that I want to pass a bash variable to.

bash.sh

while read -r db
do
Printf  "%s\n" ${db} "Found"
done < path/to/file.txt

output: db1
db2
db3

file.txt

db1
db2
db3

python.py

print(${db},+"_tables.replicate.fix")

I need an output of : db1
db2
db3

How can the python file know what the db variable holds in the bash file?

Best Answer

The easiest way to "export" the shell db variable to a program that the script runs would be to pass it as an argument, and then the python command can read it from sys.argv.

It might look like this:

while IFS= read -r db
do
printf  "%s\n" "${db} Found"
python -c 'import sys; print("db: %s" % sys.argv[1])' "$db"
done < path/to/file.txt
Related Question