I'm currently having problems to execute a command from a shell variable.
In general the following works as expected:
COMMAND="echo A" echo $COMMAND $COMMAND
produces:
echo A A
But if I do
COMMAND="su aUser -s /bin/bash -c 'echo A'" echo $COMMAND $COMMAND
I get
su aUser -s /bin/bash -c 'echo A' Password: A': -c: line 0: unexpected EOF while looking for matching `'' A': -c: line 1: syntax error: unexpected end of file
If I enter the line
su aUser -s /bin/bash -c 'echo A'
directly it works as expected.
It seems my assumption that $COMMAND is equal to entering the content as command directly is wrong.
1) Does anyone know how I can run the command from a variable?
2) What exactly is the difference between
COMMAND="command" $COMMAND
and
command
?
Single quotes(') and backslash(\) are used to escape double quotes in bash shell script. We all know that inside single quotes, all special characters are ignored by the shell, so you can use double quotes inside it. You can also use a backslash to escape double quotes.
Normally, $ symbol is used in bash to represent any defined variable. But if you use escape in front of $ symbol then the meaning of $ will be ignored and it will print the variable name instead of the value. Run the following commands to show the effects of escape character (\).
Arrays are useful to keep your parameters whole:
command=(su aUser -s /bin/bash -c 'echo A')
and invoke it exactly like this:
"${command[@]}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With