将MySQL“SELECT”查询传递给shell变量
这个问题在这里已经有了答案:
像这样使用mysql命令的-s
和-N
选项。
sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -e "INSERT INTO service_status_batch VALUES ();"
batch_id=`sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -s -N -e "SELECT MAX(id) as maxid FROM service_status_batch;"`
echo "Value of the id is:" $batch_id
请参阅-s和-N的详细信息:
--silent, -s
Silent mode. Produce less output. This option can be given multiple
times to produce less and less output.
This option results in nontabular output format and escaping of
special characters. Escaping may be disabled by using raw mode; see
the description for the --raw option.
--skip-column-names, -N
Do not write column names in results.
编辑3:糟糕的解释 - 我试图展示如何获得价值,因为它可以根据需要使用:
sudo echo $(echo "SELECT MAX(id) as maxid FROM service_status_batch" | mysql dbnamehere -uUser -pPassword)
EDIT1:显然是变量版本
EDIT2:按照建议使用shellcheck.net修正变量赋值。 谢谢。
编辑3:最后一次编辑在mysql命令之前添加sudo,因为如果没有root用户以外的用户,它将无法正常工作。
batch_id=$(echo "SELECT MAX(id) as maxid FROM service_status_batch" | sudo mysql dbnamehere -uUser -pPassword)
链接地址: http://www.djcxy.com/p/57207.html