How to execute a bash command stored as a string with quotes and asterisk
Have you tried:
eval $cmd
For the follow-on question of how to escape *
since it has special meaning when it's naked or in double quoted strings: use single quotes.
MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"
Bonus: It also reads nice: eval mysql query ;-)
Use an array, not a string, as given as guidance in BashFAQ #50.
Using a string is extremely bad security practice: Consider the case where password
(or a where clause in the query, or any other component) is user-provided; you don't want to eval
a password containing $(rm -rf .)
!
Just Running A Local Command
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
"${cmd[@]}"
Printing Your Command Unambiguously
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'
Running Your Command Over SSH (Method 1: Using Stdin)
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host 'bash -s' <<<"$cmd_str"
Running Your Command Over SSH (Method 2: Command Line)
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host "bash -c $cmd_str"
try this
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd