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


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

output: db1 db2 db3





I need an output of : db1 db2 db3

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

  • I see no connection here between Bash script and Python script. Guessing that it would be called after the printf line in Bash?
    – pbm
    Dec 10, 2019 at 17:16
  • are you asking how to write to a file in Bash then read from that same file in Python?
    – CyberStems
    Dec 10, 2019 at 17:28
  • OP is possibly asking how to do this within a bash heredoc. or, maybe how to use the export option to export the variable and then source later from a script.
    – Rakib Fiha
    Dec 10, 2019 at 17:39
  • 2
    ... or perhaps they are asking how to use sys.argv? Dec 10, 2019 at 17:50
  • 1
    unix.stackexchange.com/a/74246/117549 might help -- export the variable then use os.environ; or use unix.stackexchange.com/questions/237443/… and pass it as an argument.
    – Jeff Schaller
    Dec 10, 2019 at 18:20

1 Answer 1


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
printf  "%s\n" "${db} Found"
python -c 'import sys; print("db: %s" % sys.argv[1])' "$db"
done < path/to/file.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .