Passing a MySQL "SELECT" query to a shell variable [duplicate] - mysql

This question already has answers here:
How do I set a variable to the output of a command in Bash?
(15 answers)
Closed 6 years ago.
Lets say I have a query first that inserts certain values in a table and the next query is to display the maximum value of one of the columns and then store that in a variable. I then need to display that variable such that it shows the max value.
For example:
sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -e "INSERT INTO service_status_batch VALUES ();"
batch_id= sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -e "SELECT MAX(id) as maxid FROM service_status_batch;"
echo "Value of the id is:" $batch_id
This echo command should then show the value of the variable. However it ends up showing me the value of the select query in the form of a table and not the value of the variable.
Is there a particular way to assign the query value to a variable in shell script?
I have attached the select query value that it shows.

Use -s and -N options with mysql command like this.
sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -e "INSERT INTO service_status_batch VALUES ();"
batch_id=`sudo mysql -u$mysql_user -p$mysql_pwd -h $mysql_host --database $db_name -s -N -e "SELECT MAX(id) as maxid FROM service_status_batch;"`
echo "Value of the id is:" $batch_id
Refer the details for -s and -N :
--silent, -s
Silent mode. Produce less output. This option can be given multiple
times to produce less and less output.
This option results in nontabular output format and escaping of
special characters. Escaping may be disabled by using raw mode; see
the description for the --raw option.
--skip-column-names, -N
Do not write column names in results.

EDIT3: Bad explanation - I was trying to show how to get the value considering it could be used as necessary:
sudo echo $(echo "SELECT MAX(id) as maxid FROM service_status_batch" | mysql dbnamehere -uUser -pPassword)
EDIT1: variable version obviously
EDIT2: corrected variable assignment by using shellcheck.net as suggested. thanks.
EDIT3: one last edit to add sudo right before mysql command as it won't work without it for users other than root.
batch_id=$(echo "SELECT MAX(id) as maxid FROM service_status_batch" | sudo mysql dbnamehere -uUser -pPassword)

Related

Why is this bash variable blank when taking output from mysql?

I am trying to take the output from a MySQL query in bash and use it in a bash variable, but it keeps coming up blank when used in the script, but works perfectly from the terminal. What's wrong here?
I've tried changing the way the statement is written and changing the name of the variable just in case it was somehow reserved. I've also done a significant amount of searching but it turns out if you but 'bash', 'blank', and 'variable' in the search it usually comes up with some version of how to test for blank variables which I already know how to do.
tempo=$(mysql -u "$dbuser" -p"$dbpass" -D "$database" -t -s -r -N -B -e "select user from example where user='$temp' > 0;")
printf "the output should be: $tempo" # This is a test statement
The end result should be that the $tempo variable should either contain a user name from the database or be blank if there isn't one.
I think there is some error with your sql statement at user = '$temp' > 0.
But to get the result from MySql you have to redirect the standard error (stderr) to the standard output (stdout), you should use 2>&1.
Most probably you will run into MySql error but try running this on terminal.
tempo=$((mysql -u "$dbuser" -p"$dbpass" -D "$database" -t -s -r -N -B -e "select user from example where user='$temp' > 0;") 2>&1)
The solution was to echo the result of the sql query like this:
tempo=$(echo $(mysql -u "$dbuser" -p"$dbpass" -D "$database" -s -N -B -e "select user from example where user='$username' > 0;"))
Now I'm left with logic issues but I think I can handle that.

connect to mysql db and execute query and export result to variable - bash script

I want to connect to mysql databse and execute some queries and export its result to a varibale, and do all of these need to be done entirely by bash script
I have a snippet code but does not work.
#!/bin/bash
BASEDIR=$(dirname $0)
cd $BASEDIR
mysqlUser=n_userdb
mysqlPass=d2FVR0NA3
mysqlDb=n_datadb
result=$(mysql -u $mysqlUser -p$mysqlPass -D $mysqlDb -e "select * from confs limit 1")
echo "${result}" >> a.txt
whats the problem ?
The issue was resolved in the chat by using the correct password.
If you further want to get only the data, use mysql with -NB (or --skip-column-names and --batch).
Also, the script needs to quote the variable expansions, or there will be issues with usernames/passwords containing characters that are special to the shell. Additionally, uppercase variable names are usually reserved for system variables.
#!/bin/sh
basedir=$(dirname "$0")
mysqlUser='n_userdb'
mysqlPass='d2FVR0NA3'
mysqlDb='n_datadb'
cd "$basedir" &&
mysql -NB -u "$mysqlUser" -p"$mysqlPass" -D "$mysqlDb" \
-e 'select * from confs limit 1' >a.txt 2>a-err.txt
Ideally though, you'd use a my.cnf file to configure the username and password.
See e.g.
MySQL Utilities - ~/.my.cnf option file
mysql .my.cnf not reading credentials properly?
Do this:
result=$(mysql -u $mysqlUser -p$mysqlPass -D $mysqlDb -e "select * from confs limit 1" | grep '^\|' | tail -1)
The $() statement of Bash has trouble handling variables which contain multiple lines so the above hack greps only the interesting part: the data

Search for specific string/pattern in MySQL Database from Terminal/SSH/Commandline

I have a Magento database in which I want to search for a particular string/pattern.
But the database's size is too large so I cannot export the database to .sql file and then search into that file(editor even Geany crashes opening such large files).
So how can I do a search the database for a perfect match of [string/pattern] and display fulltext information as result, through only using command-line and MySQL Database credentials ?
I tried below command, but it requires username to be given as -u[USERNAME], also it doesn't display full query or result in terminal window.
mysqldump -p[PASSWORD] [DATABASE] --extended=FALSE | grep [pattern] | less -S
Anyone have any solutions for this ?
You can first log into MySQL CLI as especified in http://dev.mysql.com/doc/refman/5.7/en/connecting.html
mysql --host=localhost --user=myname --password=mypass mydb
So, you can use a query command to find your pattern. If you know the table you want to search such as the column it make the thinks easy. The SELECT statement is like this:
SELECT column FROM table WHERE column LIKE '%pattern%';
http://dev.mysql.com/doc/en/select.html
If you don't know the table's name, you can list all and try to find by the meaning.
SHOW TABLES;
Edited with better code
You didn't say if this was a one off or not but this will check all tables in a schema for a value.
First in your home directory set up a file named .my.cnf with the following contents and change its permissions to 700 (Replace [USERNAME] and [PASSWORD] with your username and password.
[client]
user=[USERNAME]
password="[PASSWORD]"
Then execute the following (Replacing [DATABASE] and [CHECKSTRING] with your database and the check string)
mysql [DATABASE] --silent -N -e "show tables;"|while read table; do mysql [DATABASE] --silent -N -e "select * from ${table};"|while read line;do if [[ "${line}" == *"[CHECKSTRING]"* ]]; then echo "${table}***${line}";fi;done;done
If checking for 51584 the result would be something like
test_table***551584,'column 2 value','column 3 value'
test_table5***'column 1 value',251584,'column 3 value'
If you want to know which column had the value then select from INFORMATION_SCHEMA.COLUMNS and add another nest.
mysql [DATABASE] --silent -N -e "show tables;"|while read table; do mysql [DATABASE] --silent -N -e "select column_name from information_schema.columns where table_schema='[DATABASE]' and table_name = '${table}';"|while read column; do mysql [DATABASE] --silent -N -e "select ${column} from ${table};"|while read line;do if [[ "${line}" == *"[CHECKSTRING]"* ]]; then echo "${table}***${column}***${line}";fi;done;done;done
If checking for 51584 the result would be something like
test_table***column1***551584
test_table5***column2***251584
First of all you need to login into database with correct username and password by below command.
sudo mysql -u root -p
then check the database in which you want to operate operation.
eg.
SHOW DATABASES;
USE Test;
now your database is ready for operation through terminal. Here I assume my database name is "Test".
Now for String/pattern matching use command as below or follow the link http://www.mysqltutorial.org/mysql-regular-expression-regexp.aspx.
SELECT
column_list
FROM
table_name
WHERE
string_column REGEXP pattern;

How do you get table-formatted output from MySQL in non-interactive mode? [duplicate]

This question already has answers here:
MYSQL differs in Output from script
(2 answers)
Closed 3 years ago.
I like the table output that the mysql client program produces in interactive mode, but if I try to run a sql script like this:
mysql -uroot mydb < myscript.sql
I only get tab-separated output.
mysql -uroot mydb -e 'select * from mytable'
does produce the output in the desired table format, however.
How can I get the first command to produce table-formatted output? I don't want HTML output, but the terminal character output with aligned columns and headers.
Add the -t option to mysql (table).
mysql -t -uroot mydb < myscript.sql
mysql -t -uroot mydb -e 'select * from mytable'
Use \P less -S option before running the query
mysql> \P less -S
PAGER set to 'less -S'

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

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