You have a variable in a Bash script that helps you compose a new Bash command. You want to create a complex and dynamic Bash command. This variable includes one or more spaces in it.
You can echo the commands and verify that these are valid Linux commands. You run them and they test out. But to run automatically in a script, you are finding that it can be difficult. What can be done to get the script to run successfully with having spaces in the commands?
Have the script create a new [disposable] script with the correct commands appended into it. Have that disposable script be run. That disposable script can then be deleted.
Here is an example of doing complex sed commands with /etc/ssh/sshd_config:
var1=65 # You could introduce logic to have a more dynamic line number assignment (e.g., grep -n)
var2=91 # You could introduce logic to have a more dynamic line number assignment (e.g., grep -n)
comm1="sed -i \""$var1"s/KererosAuthentication no/KerberosAuthentication yes/\" /etc/ssh/sshd_config"
echo $comm1 >> /tmp/intermediate.sh # this will create a temporary script
comm2="sed -i \""$var2"s/X11UseLocalhost no/X11UseLocalhost yes/\" /etc/ssh/sshd_config"
echo $comm2 >> /tmp/intermediate.sh
rm /tmp/intermediate.sh # delete this temporary script