如何执行存储为带引号和星号的字符串的bash命令

时间:2010-01-05 09:55:05

标签: bash scripting escaping quotes

我尝试执行以下命令:

mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig"

我将它存储在一个字符串中:

cmd="mysql AMORE -u username -ppassword -h localhost -e\"SELECT  host  FROM amoreconfig\""

测试它:

echo $cmd
mysql AMORE -u username -ppassword -h localhost -e"SELECT host FROM amoreconfig"

尝试执行:

$cmd

我得到了mysql的帮助页面:

mysql  Ver 14.14 Distrib 5.1.31, for pc-linux-gnu (i686) using readline 5.1
Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license
Usage: mysql [OPTIONS] [database]
(...)

我想我正在做一些关于引号的错误但却无法找出问题所在。

5 个答案:

答案 0 :(得分:314)

你试过了吗?

eval $cmd

关于如何逃避*的后续问题,因为它在裸体或双引号字符串中具有特殊含义时:使用单引号。

MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"

奖励:它也很好看:eval mysql查询; - )

答案 1 :(得分:40)

使用数组,而不是字符串,如BashFAQ #50中的指导。

使用字符串极其糟糕的安全措施:考虑用户提供password(或查询中的where子句或任何其他组件)的情况;您不希望eval包含$(rm -rf .)的密码!

刚刚运行本地命令

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
"${cmd[@]}"

明确地打印命令

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'

通过SSH运行命令(方法1:使用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"

通过SSH运行命令(方法2:命令行)

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"

答案 2 :(得分:23)

试试这个

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

答案 3 :(得分:2)

你甚至不需要“eval”。只需在字符串前放一个美元符号:

cmd="ls"
$cmd

答案 4 :(得分:-3)

为了消除对cmd变量的需要,您可以这样做:

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