Declare variable in Bash?

2019-08-22 05:28发布

I'm connected to my DB from the bash. I do a select count of an array and I want to stock the return in a variable. How can I do that?

I did:

var=`"select count(*) from shop_tab where catalog <> ''" | mysql -h abcdcef.com --port=3306 --user=root --password=hbbfe shop`

The request return a number but it doesn't stock into the variable.

Thanks!

EDIT: It works with this command line:

myvar = $(echo "select count(*) from shop_tab where catalog <> '';" | mysql -h abcdcef.com --port=3306 --user=root --password=hbbfe shop)

2条回答
混吃等死
2楼-- · 2019-08-22 06:12

I think you are forgetting an echo in the pipe? Like this:

var=`echo "select count(*) from shop_tab where catalog <> ''" | mysql -h abcdcef.com --port=3306 --user=root --password=hbbfe shop`
查看更多
贼婆χ
3楼-- · 2019-08-22 06:19

An easier way is :

var=$(mysql -h abcdcef.com --port=3306 --user=root --password=hbbfe --batch --skip-column-names -Dshop -e "select count(*) from shop_tab where catalog <> ''")

Moreover, I'll preconize the use of function in order to easily add options to the MySQL command without having to modifying all your script.

function MysqlQuery() {
    mysql -h abcdcef.com --port=3306 --user=root --password=hbbfe --batch --skip-column-names -D "$1" -e "$2";
}

va=$(MysqlQuery Shop "SELECT COUNT(*) FROM shop_tab WHERE catalog <> ''")
vaABC=$(MysqlQuery Shop "SELECT COUNT(*) FROM shop_tab WHERE catalog <> 'abc'")
vadef=$(MysqlQuery Shop "SELECT COUNT(*) FROM shop_tab WHERE catalog <> 'def'")
# ...

I find this more readable too...

查看更多
登录 后发表回答