如何执行存储与报价和星号的字符串bash命令[复制]如何执行存储与报价和星号的字符串bash命令[复

2019-05-08 21:19发布

这个问题已经在这里有一个答案:

  • 为什么外壳忽略通过变量传递给它的参数报价? [重复] 3个答案

我尝试执行以下命令:

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]
(...)

我想我做一些简单的错误的报价,但不能查出是什么问题。

Answer 1:

你有没有尝试过:

eval $cmd

对于如何逃脱的后续问题* ,因为它具有特殊的意义,当它的裸或双引号字符串:使用单引号。

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

奖励:它也读漂亮:EVAL MySQL查询;-)



Answer 2:

使用数组,而不是字符串,如为指导给出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:使用标准输入)

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"


Answer 3:

试试这个

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


Answer 4:

你并不需要“EVAL”连。 只要把一个美元符号在前面的字符串:

cmd="ls"
$cmd


Answer 5:

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

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


文章来源: How to execute a bash command stored as a string with quotes and asterisk [duplicate]