scripting - How to execute a bash command stored as a string with quotes and asterisk

ID : 10065

viewed : 55

Tags : bashscriptingescapingquotesbash

Top 5 Answer for scripting - How to execute a bash command stored as a string with quotes and asterisk

vote vote

99

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 ;-)

vote vote

88

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" 
vote vote

78

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"' $ eval $cmd 
vote vote

64

You don't need the "eval" even. Just put a dollar sign in front of the string:

cmd="ls" $cmd 
vote vote

59

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"' 

Top 3 video Explaining scripting - How to execute a bash command stored as a string with quotes and asterisk

Related QUESTION?