0

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.

3
  • Never try to use interpolation to build a script, whether it be SQL, Python, or any other language. Commented Feb 25, 2022 at 16:20
  • just curious why? Commented Mar 30, 2022 at 15:41
  • en.wikipedia.org/wiki/SQL_injection Commented Mar 30, 2022 at 16:01

1 Answer 1

2

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

You can use the var=value command syntax and omit the export (note the lack of a semicolon)

$ funny=879 fonny=978 python3 -c 'import os; print(os.environ["funny"], os.environ["fonny"])'
879 978
Sign up to request clarification or add additional context in comments.

1 Comment

You can also pass an argument to the script: python3 -c 'import sys; print(f"hello {sys.argv[1]}")' "$funny"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.