简体   繁体   中英

Passing a shell variable to inline python in a shell script

I have a simple shell script where i want to be able to pass variables to some inline python i will write. For example like this

funny=879
echo $funny
python -c "
print(f"hello {$funny}")
"

However this prints

879
  File "<string>", line 2
    print(fhello
               ^
SyntaxError: unexpected EOF while parsing
(pipeline) $ 

Any thoughts on what i could be doing wrong? I know i am setting the variable correct because when i do echo it prints out the variable so it is definitely set correct but for some reason python script is not able to use it.

It's because you're using outer double quotes.

python -c "print(f"hello {$funny}")"

Gets turned into:

python -c print(fhello {879})

So python is passed 2 separate strings.

The inner double quotes would need to be escaped in order to get passed through to python.

$ funny=879; python3 -c "print(f\"hello $funny\")"
hello 879

Instead of messing around with quoting - if you export your variables you can access them from python using the os.environ dict.

$ export funny=879; python -c 'import os; print(os.environ["funny"])'
879

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM