1

I'm trying to pass a bash variable to be parsed by a python script, as follows:

#!/bin/bash

command="--var1 var1 --var2 'var 2'"
echo $command
python test.py $command

python script (test.py)

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--var1", action="store", dest="var1")
parser.add_argument("--var2", action="store", dest="var2")

args = parser.parse_args()
print args.var1, args.var2

However, it fails due to there being whitespace, which I'm not sure how to escape error: unrecognized arguments: 2'. Running python test.py --var1 var1 --var2 'var 2' from the command line works fine though. Is there any way around this?

1
  • 2
    In addition to the answers below, you do not need the action and store in this simple case, the variables will be created by the parser implicitly (as names of your options), so this should be enough: parser.add_argument("--var1") and parser.add_argument("--var2") Commented Aug 3, 2020 at 18:53

2 Answers 2

6

Use arrays to store multi-word strings. Regular string variables suffer from unavoidable whitespace and quoting problems whereas arrays handle them without issue.

command=(--var1 var1 --var2 'var 2')
echo "${command[@]}"
python test.py "${command[@]}"

"${command[@]}" is the syntax for expanding an array while preserving each element as a separate word. Make sure to use the quotes; don't leave them out.

Sign up to request clarification or add additional context in comments.

Comments

1

When you use an expansion without quotes, bash expands it, including any glob expansions or other things found within. It also wrecks any whitespace. This is why using quotes is so very recommended.

In other words, by the time the arguments get to python, they're already wordsplit, and can't be put back together.

If you need to put a set of arguments in a name, consider using an array, like

command=('--var1' 'var1' '--var2' 'var 2')

and the expansion like

python test.py "${command[@]}"

Using an array, bash will respect the argument setup just like it was in the array.

Comments

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.