26

Basically I want to be able to invoke a given command, in this case mysql -uanon -ppwd -db mydb -e "select count(*) from table1". And then take this commands result (the count on that table) and place it in a variable in bash script. What is the simplest way to achieve this?

2 Answers 2

41

You most likely want to use batch mode (-B) and disable column names (--disable-column-names) for non-interactive mysql output:

out=$(mysql -B -db mydb -uanon -ppwd --disable-column-names  -e "select count(*) from table1";)
1
  • For Linux newbies, make sure there are no spaces between variable name, the = sign and the expression that follows. Bad things can happen. Commented Jun 21, 2017 at 23:52
14
$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1")
$ echo $A

In other words, use the $() syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.