开发者

Why am I getting this error while trying to retrieve data from MySQL db using bash script in Linux?

I am trying to retrieve email address from MySQL database.

#!/bin/bash
MYSQLHOST="192.168.1.1"                                               
MYSQLDB="nuni"
MYSQLUSER="root"
MYSQLPASS="rootpass"
MYSQLOPTS="--user=${MYSQLUSER} --password=${MYSQLPASS} --host=${MYSQLHOST} ${MYSQLDB}"
EMAIL=echo "SELEC开发者_C百科T email FROM Edsrn WHERE userid = 1235" | mysql ${MYSQLOPTS}
echo "E-mail: $EMAIL"

What is wrong with it? I says "command not found". Please help!


I recommend using the -e parameter to evaluate SQL statements instead. This should be what you're looking for:

#!/bin/bash
MYSQLHOST="192.168.1.1"                                               
MYSQLDB="nuni"
MYSQLUSER="root"
MYSQLPASS="rootpass"
MYSQLOPTS="-s --user=${MYSQLUSER} --password=${MYSQLPASS} --host=${MYSQLHOST} ${MYSQLDB}  -e "
EMAIL=$(mysql ${MYSQLOPTS} "SELECT email FROM Edsrn WHERE userid = 1235" | tail -n 1)
echo "E-mail: $EMAIL"

Note the tail is needed since the output from mysql looks like this:

column
value


It's trying to run "SELECT email FROM Edsrn WHERE userid = 1235" with $EMAIL set to "echo". If you wanted the result of your command to be put in $EMAIL then you got the syntax wrong.

EMAIL=$(echo "SELECT email FROM Edsrn WHERE userid = 1235" | mysql ${MYSQLOPTS})

Also, BASH FAQ entry #50.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜