在 Bash 中声明变量?

在 Bash 中声明变量?

问题描述:

我从 bash 连接到我的数据库.我做了一个数组的选择计数,我想将回报存入一个变量中.我该怎么做?

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?

我做到了:

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.

谢谢!

它适用于这个命令行:

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

更简单的方法是:

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

此外,我将预先确定函数的使用,以便轻松地向 MySQL 命令添加选项,而无需修改所有脚本.

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...