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?
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 ...]
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.
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.
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";)
$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1") $ echo $A
In other words, use the $() syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With