Trying to check if a Mysql user exists in a bash script - mysql

I am trying to check if a MYSQL user exists. This is as far as I have got. I fall down on capturing the answer from the output.
#!/bin/bash
echo -e "What is the MYSQL username called"
read DBUSER
if [ -z "$DBUSER" ]
then
exit
mysql -uUSER -pPASS -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')";
if
yes
do this
else
do this
this is the output I am getting
+-----------------------------------------------------+
| EXISTS(SELECT 1 FROM mysql.user WHERE user = 'bob') |
+-----------------------------------------------------+
| 1 |
+-----------------------------------------------------+
Can any one help please

Thanks very much for your help. Here is the final result working.
It needs the -sse
RESULT_VARIABLE="$(mysql -uUSER -pPASS -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')")"
if [ "$RESULT_VARIABLE" = 1 ]; then
echo "TRUE"
else
echo "FALSE"
fi

Assigning the result to a variable can be done like this:
RESULT_VARIABLE="$(mysql -uUSER -pPASS -se "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')")"
And you can also alias a column in MySQL, btw.
SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER') AS does_it_exist

Related

Loop through result set of mysql in Bash - routines

I want to make specific .sql file for each of my routines.
#!/bin/bash
routine_names=$(mysql mydb --execute="SELECT
*
FROM
information_schema.routines
WHERE
routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
AND routine_schema = 'mydb';"|cut -f1)
for routine in "$routine_names"
do
if [ -e "${routine}.sql" ]
then
echo "ok"
else
content_procedure=$(mysql mydb--execute="SHOW CREATE PROCEDURE $routine;")
echo "$content_procedure" >> masoud.txt
fi
done
my routine_names variable is a list of my procedures. like this:
SP_ONE
SP_TWO
SP_THREE
I want to loop of these result. but I think the result is not an array. because routine variable has all content.
wrap your mysql mydb ... command with ()
routine_names=($(mysql mydb --execute="SELECT
*
FROM
information_schema.routines
WHERE
routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
AND routine_schema = 'mydb';"|cut -f1))
I was curious and got the idea from here.
Just another case how I fix my problem
#!/bin/bash
mysql -u USER -p -h localhost -D database1 -e "SELECT ID FROM prodTable WHERE display=1 AND new=1 AND exDate<DATE_SUB(CURDATE(),INTERVAL 2 YEAR)" | while read ID;
do
echo "The following product has been moved: $ID"
done

Loop through result set of mysql in Bash

I have a simple bash script. I wish to get an exact count of the number of rows in each table of the database.
#!/bin/bash
TABLES_OLD=$( mysql -u user -ppassword MySchema --batch --skip-column-names -e"SHOW TABLES FROM MySchema" )
for table in "${TABLES_OLD[#]}"
do
QUERY="SELECT COUNT(*) FROM ${table}"
echo "${QUERY}"
done
The script prints:
SELECT COUNT(*) FROM Table 1
Table2
Table3
Table4
etc...
Clearly this is not what I want, and I don't even understand how what is happening is possible. What am I doing wrong?
Try this, put the tables into an array then loop thru the results
db_host='host'
db_user='user'
db_pass='password'
db='your_db'
read -ra var_id <<< $(mysql -h $db_host -u $db_user -p$db_pass $db -sse "show tables from $db")
for i in "${var_id[#]}";
do
results=$(mysql -h $db_host -u $db_user -p$db_pass $db -sse "select count(*)from $i")
echo "$i $results"
done
This should do it :
#/bin/bash
mysql -u user-ppassword -e "SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'your_data_base_name';"
Replace echo with eval
The code will be
#!/bin/bash
TABLES_OLD=$( mysql -u user -ppassword MySchema --batch --skip-column-names -e"SHOW TABLES FROM MySchema" )
for table in "${TABLES_OLD[#]}"
do
QUERY="SELECT COUNT(*) FROM ${table}"
eval "${QUERY}"
done

How to get a value without characters like "- , + "?

This is the normal output:
mysql> select module_id from Modules where Module_name = 'STP_XENA';
+-----------+
| module_id |
+-----------+
| 3 |
+-----------+
1 row in set (0.00 sec)
Can I get answer for the query as only "3"
I need something like,
mysql> select module_id from Modules where Module_name = 'STP_XENA';
3
mysql>
But not from bash or console. Is there any option to do this ?
You cannot do it inside MySQL editor, AFAIK. If you execute the script from console, then adding -B switch can get you desired result.
> mysql -B -u username -p password -e "select module_id from Modules where Module_name = 'STP_XENA';" DBNAME
will yield value with column name:
module_id
3
Also, if you add --skip-column-names
> mysql -B --skip-column-names -u username -p password -e "select module_id from Modules where Module_name = 'STP_XENA';" DBNAME
will yield only value (minus column name):
3
HTH
EDIT: You may start mysql with --skip-column-names switch. I am not sure about -B though. If you are able to start with -B, then great.
You want to use the query result in something like a bash script?
If so, you could do with:
mysql -u{user} -p{password} -s -N -e "select module_id from Modules where Module_name = 'STP_XENA'" database_name
Example:
module_id = `mysql -u{user} -p{password} -s -N -e "select module_id from Modules where Module_name = 'STP_XENA'" database_name`
echo $module_id

Pass MySQL variables to script from command line

I have a MySQL update script I'd like to run from the command line, but I want to be able to pass a stage domain variable to the script.
I know this won't work, but it's the best way I can describe what I'm trying to do:
$ -uroot -hlocalhost mydatabase --execute "SET #domain = 'mydomain.dev' " < ./sql/update_domain.sql
Inside the script, I'm using the #domain variable, to update some configuration variables in a config table, using commands like this:
UPDATE my_cfg SET value = #domain WHERE name = 'DOMAIN';
Basically I want to prefix the SET #domain on the update_domain.sql file.
Any ideas how I can rectify my approach?
In your BATCH File :
mysql -e "set #domain=PARAMVALUE;source ./sql/update_domain.sql"
And in you SQL file :
UPDATE my_cfg SET value = #domain WHERE name = 'DOMAIN';
you can do that with sed like this:
echo "UPDATE my_cfg SET value = '#domain#' WHERE name = 'DOMAIN'" | sed 's/#domain#/mydomain.dev/' | mysql -uusername -ppassword dbname
or update.sql has UPDATE:
cat update.sql | sed 's/#domain#/mydomain.dev/' | mysql -uusername -ppassword dbname
This works for me:
system("(echo \"SET #domain = 'newstore.personera.abc';\"; cat sql/set_domain.sql) > /tmp/_tmp.sql")
system("mysql -uroot -hlocalhost newstore.personera.dev < /tmp/_tmp.sql")
system("rm /tmp/_tmp.sql")
...calling with system() from Capistrano.
I've found a better solution.
--init-command=name SQL Command to execute when connecting to MariaDB server.
mysql --init-command="SET #foo = 1; SET #bar = 2" -e "SELECT #foo, #bar, VERSION()"
Output:
+------+------+-------------------------------------+
| #foo | #bar | VERSION() |
+------+------+-------------------------------------+
| 1 | 2 | 10.6.3-MariaDB-1:10.6.3+maria~focal |
+------+------+-------------------------------------+
It also works with file redirection.

bash - SQL Query Outputs to variable

Im new in bash scripting.
I want to save sql-query outputs in variable, but
actually I must connect for every query to mysql with:
mysql -u $MYUSER -p$MYPASS -D database
and want to save every output in seperatly variable
sample query is: SELECT domain FROM domains WHERE user='$USER'
to
$variable1 = FIRST_OUTPUT
$variable2 = 2ND_OUTPUT
thank you
Taken from bash script - select from database into variable, you can read the query result into a variable.
Example
mysql> SELECT * FROM domains;
+-------+---------+
| user | domain |
+-------+---------+
| user1 | domain1 |
| user2 | domain2 |
| user3 | domain3 |
+-------+---------+
Usage
$ myvar=$(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains")
$ echo $myvar
domain1 domain2 domain3
echo is the bash command for output. You can then split $myvar into separate variables:
$ read var1 var2 var3 <<< $myvar
$ echo $var1
domain1
$ echo $var2
domain2
You can combine these two commands into a single one:
read var1 var2 var3 <<< $(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains")
It is possible to store the results into arrays (useful if you don't know how many records there):
$ read -ra vars <<< $(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains")
$ for i in "${vars[#]}"; do
$ echo $i
$ done
domain1
domain2
domain3
Another way of doing is:
dbquery=`mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains"`
dbquery_array=( $( for i in $dbquery ; do echo $i ; done ) )
The first line stores all the output from the query in a varriable dbquery in a array-like-way. The second line converts the dbquery into an array dbquery_array with a simple for loop.
I did this
variable=mysql -u root -ppassworrd database << EOF
select MAX(variable) AS a from table where variable2 = 'SOMETEXT' AND day(datevalue) >= 22;
EOF
I hope it helps