Let's say I have a script script.py
accepting some command line arguments, and a bash script main.sh
that calls it with multiple combinations as defined below. Now contrary to my example below the variables MYARGS
andMOREARGS
contain a larger number of arguments (10-20 or so). For this reason I thought it would be more readable to split these strings up into multiple lines, with one argument/value pair per line. Is there a way to use multiline strings or are there any ways we can break it up?
MYARGS="--a=\"asdf\" --b=2.61828" # <- break this into two or more lines?
MOREARGS="--c 31415"
python script.py $MYARGS
python script.py $MYARGS $MOREARGS
where script.py
is
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--a')
parser.add_argument('--b')
parser.add_argument('--c')
args = parser.parse_args()
print(args)
CodePudding user response:
A quoted string can span multiple lines. This script:
MYARGS="-a=asdf
-b=2.1828
-c=foo
"
echo $MYARGS
Produces as output:
-a=asdf -b=2.1828 -c=foo
This works fine, but it ends up getting tricky when you have arguments that contain whitespace. In that case, it generally makes more sense to use arrays, assuming that you're working with Bash (or another modern shell):
MYARGS=(
-a="this has whitespace"
-b=2.1828 # I can even include inline comments!
-c=foo
)
MOREARGS="--c 31415"
python script.py "${MYARGS[@]}"
python script.py "${MYARGS[@]}" $MOREARGS
In the above, MYARGS
is an array, but MOREARGS
is a simple scalar variable.