0

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?

7
  • I see no connection here between Bash script and Python script. Guessing that it would be called after the printf line in Bash?
    – pbm
    Commented 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
    Commented 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
    Commented Dec 10, 2019 at 17:39
  • 2
    ... or perhaps they are asking how to use sys.argv? Commented 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
    Commented Dec 10, 2019 at 18:20

1 Answer 1

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
do
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.