0

I'm trying to run a command in a bash variable, like this:

cmd="python -m mymodule 'argument 123 456' argument2=32 argument3=234"
$cmd

It looks like it is splitting the command line arguments in the first string even though it is surrounded with single quotes:

['argument', '123', '456', 'argument2=32', 'argument3=234']

Is there anything I can do to prevent this? I've tried to use esacped double-quotes \", backticks `, but nothing works, it will still split the first command line argument on the spaces.

AdminBee
  • 22,803

1 Answers1

0

In your case, I would recommend storing the command and its arguments in an array:

cmd=( "python" "-m" "mymodule" "argument 123 456" "argument2=32" "argument3=324" )

and running it as

"${cmd[@]}"
  • The key is dereferencing the array content as ${cmd[@]} with an @, and placing it in double-quotes, because the shell will then expand this to a list of array elements in a way as if each element were double-quoted, thereby preventing word-splitting (see e.g. this related Q&A for more on that).

  • At the same time, you must add each token that the shell is to treat separately as its own array element (so e.g. "-m" and "mymodule" must be separate elements - stating it as "-m mymodule" will likely fail, being mis-interpreted as either a value-less option m mymodule or an option m with value mymodule including the leading space - see this Q&A for more insight).

AdminBee
  • 22,803