I'm going nuts trying to figure out how to correctly pass arguments from a shell script to python when backticks are involved.
This is my ./foo.sh
#!/bin/bash
EXEC_SCRIPT="./foo.py -c $1"
result=`${EXEC_SCRIPT}`
echo ${result}
This is my ./foo.py
#!/usr/bin/python
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-c', required=True)
args,u = ap.parse_known_args()
args = vars(args)
print ("I GOT {}".format(args['c']))
I do:
./foo.sh ABC
and I get :
I GOT ABC
Perfect.
But then I do:
./foo.sh "Hello World"
And I get:
I GOT Hello
Trying to change the bash script to:
EXEC_SCRIPT="./foo.py -c \"$1\""
Produces:
I GOT "Hello
None of this is an issue if I don't use backticks. Escaped quotes work great.
What am I missing?
What I really want is the python script should get my argument, whether its 1 word or 2 without quotes.
Further clarification: Thanks to Gordon and AK47 for making the same suggestion. It looks like the root cause is I am stuffing the command in a variable called EXEC_SCRIPT. Invoking the command directly inside the backticks works. My real script is more complex and EXEC_SCRIPT
points to different values due to different conditions. What's a good way to achieve clean code which lets me figure out the right command and then invoke it at the end? Using a variable is logical, as I did, but it apparently doesn't work