小编典典

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

all

我尝试执行以下命令:

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

我想我对引号做了一些明显的错误,但无法找出问题所在。


阅读 74

收藏
2022-04-14

共1个答案

小编典典

你有没有尝试过:

eval $cmd

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

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

奖励:它也读起来不错:eval mysql query ;-)

2022-04-14