如何执行一个bash命令存储为一个带有引号和星号的string
我尝试执行以下命令:
mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig"
我把它存储在一个string中:
cmd="mysql AMORE -u username -ppassword -h localhost -e\"SELECT host FROM amoreconfig\""
testing它:
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] (...)
我想我正在做一些引用错误的东西,但无法找出问题所在。
你有没有尝试过:
eval $cmd
关于如何转义的后续问题*
因为它在裸体或双引号string中有特殊意义:使用单引号。
MYSQL='mysql AMORE -u username -ppassword -h localhost -e' QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double" eval $MYSQL "'$QUERY'"
奖金:它也读取不错:eval mysql查询;-)
使用数组而不是string,如BashFAQ#50中的指导:
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" ) # to run it locally "${cmd[@]}" # to present it to the user in unambiguous form printf 'Proposing to run: ' printf '%q ' "${cmd[@]}" printf '\n' # to run it over ssh (via stdin; safer) printf -v cmd_str '%q ' "${cmd[@]}" ssh other_host 'bash -s' <<<"$cmd_str" # to run it over ssh (without stdin; only completely safe if remote /bin/sh is bash) printf -v cmd_str '%q ' "${cmd[@]}" ssh other_host "bash -c $cmd_str"
使用string是非常糟糕的安全实践 :考虑用户提供password
(或查询中的where子句或任何其他组件)的情况; 你不想要一个包含$(rm -rf .)
的密码!
尝试这个
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"' $ eval $cmd
你甚至不需要“eval”。 只要在string前放一个美元符号:
cmd="ls" $cmd
为了消除对cmdvariables的需求,你可以这样做:
eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'