0

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)
user420574
  • 1,437
  • 5
  • 21
  • 33

2 Answers2

4

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

Arnaud F.
  • 8,252
  • 11
  • 53
  • 102
1

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`
carlpett
  • 12,203
  • 5
  • 48
  • 82