Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to invoke command and store the result in a variable?

Tags:

bash

shell

mysql

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?

like image 265
Zombies Avatar asked Apr 28 '10 15:04

Zombies


People also ask

How do you store output of command into variables?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you save the output of a command to a file in Bash?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.

How do I run a command in a Bash variable?

Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.


2 Answers

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";) 
like image 97
Jürgen Hötzel Avatar answered Oct 12 '22 22:10

Jürgen Hötzel


$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1") $ echo $A 

In other words, use the $() syntax.

like image 32
unwind Avatar answered Oct 12 '22 23:10

unwind