0

I am trying to run a python script with several arguments from bash. Some of the arguments are path names with asterisks as wildcards. However, I've been having some trouble passing the arguments into python. In attempt 1, the asterisk in ${config} got expanded by bash into a list of the files that matches the wildcard.

Attempt 1:

project_name="foo"
config="--G_ckpt /mnt/d/Documents/GAN/results/*_$name/${project_name}_g_param_epoch*.pkl --pattern */*.jpg"
python gan.py ${config}

In attempt 2, I quoted "${config}" to prevent bash from expanding the variable. However, now python seems to see the whole "$config" as a single string.

Attempt 2:

project_name="foo"
config="--G_ckpt /mnt/d/Documents/GAN/results/*_$name/${project_name}_g_param_epoch*.pkl --pattern */*.jpg"
python gan.py "${config}"

Output from my python script (attempt 2):

print(sys.argv)
>> ['gan.py', '--G_ckpt /mnt/d/Documents/GAN/results/*_$name/${project_name}_g_param_epoch*.pkl --pattern */*.jpg']

One way around this is to break "$config" into several variables eg. config0="--G_ckpt", config1="/mnt/d/Documents/GAN/results/*_$name/${project_name}_g_param_epoch*.pkl" and then python gan.py $config0 "$config1".

However, this will make my script much more complicated. In my actual script I have several dozens of these asterisk arguments.

Does anyone know a simple solution to pass path names with asterisk from bash to python as arguments?

matohak
  • 535
  • 4
  • 19
  • Not putting it in a variable first is the usual workaround. See also https://mywiki.wooledge.org/BashFAQ/050; the quick and dirty fix is to put a backslash before the characters you need to escape; but really, don't. – tripleee Jan 24 '20 at 17:56
  • The solution you suggested as "This question already has answers here" in https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables doesn't work very well for my case. I have parentheses in my path name and `eval` attempts to expand these parentheses as well. I found the best solution myself: use "set -o noglob" to disable bash's glob expansion. – matohak Jan 24 '20 at 18:15
  • 1
    I'll repeat my advice to not use variables here at all. Defintiely avoid `eval` if you can. – tripleee Jan 24 '20 at 18:34
  • Either use an array, or just don't try to store the arguments in advance. The linked question has answers that cover this. Do not use `eval` or `bash -c` -- those are just asking for even weirder bugs. – Gordon Davisson Jan 24 '20 at 20:15

0 Answers0