I'm trying to make a script which needs to save a command to be run as a string. The string in question needs to contain quotes, and when attempting to execute it bash adds additional quotation characters which in some cases causes the command to not run as expected.
Here is an example script. The command example
run in this example script obviously doesn't do anything and it will simply say command not found
, however you can still run the script and see what I'm talking about because I added -x
to the #!/bin/bash
line so that the exact command being run is printed out.
Example:
#!/bin/bash -x
#command typed explicitly
example -options "-i filename"
#command stored in string first
commandstring='example -options "-i filename"'
echo "running command: ${commandstring}"
${commandstring}
The output of running this script for me is (ignoring the two "command not found" errors):
+ example -options '-i filename'
+ commandstring='example -options "-i filename"'
+ echo 'running command: example -options "-i filename"'
running command: example -options "-i filename"
+ example -options '"-i' 'filename"'
So you can see that the first line of course is run as expected giving the command line parameter:
-i filename
However, although the echo
command prints the string in a way that would execute perfectly as well, when the string is placed on the command line it changes and the parameter being passed in becomes
'"-i' 'filename"'
which contains additional quote characters, and this is causing the actual command I'm using in my real script to fail.
Is there any way to prevent this?
echo "${commandline[@]}"
prints the line without quotes, as doesecho ${commandline[@]}
. Is there a way to also print the array with the quotes intact? – Donn Lee Dec 16 '19 at 21:04set -x
before the command andset +x
after the command. – Donn Lee Dec 16 '19 at 21:14