Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash running python inline in shell script still not working

I am on Windows and using GitBash to run shell scripts in bash that run python scripts.

I’m trying to run python inline in a bash shell script using the answer from How to execute Python inline from a bash shell.

I’m using a specific python environment, and the path is defined with an alias.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a file called .pyalias:

alias mypython='C:/users/name/mypath/python.exe test.sh'

This is a file called test.sh:

# misc notes at top, like a docstring
print("Hello")
# real file will instead say myPyScript.py etc.

Here is the problem: This is a file called main_run_all.sh:

# misc notes at top, like a docstring

shopt -s expand_aliases
source ./.pyalias

mypython test.sh

mypython -c print("Hello Again")

When I run sh main_run_all.sh, it prints "Hello" to the console (good, it is successfully running the test.sh script), but then it doesn’t run the inline command, returning the following error:

test.sh: line 8: syntax error near unexpected token `('
test.sh: line 8: `mypython -c print("Hello Again")'

>Solution :

You need to put the python code in quotes so the shell doesn’t try to parse it like shell code:

mypython -c 'print("Hello Again")' 
# ..........^....................^

If you get python code that contains both double and single quotes, quoting can be a real pain. That’s the point when you use a quoted here-doc:

python <<'END_PYTHON'
print("Hello")
print('World')
END_PYTHON
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading