MySQLSHOW Suppress Warning in Bash Script - mysql

I'm working on a simple bash script and one of the things it does is check whether a database already exists before moving on. It's simple enough code, but I'm getting a warning message whenever I try to run the script and I want to suppress that.
Here is the code:
if ! mysql -uroot -proot -e "use $NAME"; then
echo YES
else
echo NO
fi
So, as output, I get the following message when the if statement returns true:
ERROR 1049 (42000) at line 1: Unknown database 'database'
YES
How can I suppress that message? It doesn't stop the script from running, but I would prefer not to see it.

It simply tells you that the DB with the name database (which is apparently passed as a value of the $NAME variable) doesn't exist. Use the correct DB name and there'll be no warning.
To simply mute the warning redirect all the output to /dev/null as usual:
if ! mysql -uroot -proot -e "use $NAME" 2>&1 >/dev/null; then
echo YES
else
echo NO
fi

Related

How to suppress output and check whether or not a command is successful?

I am trying to write a powershell script that tests if a MySQL login is successful by using $? to check if an error occurs.
I also want to suppress all output - successful or not successful - from the command.
These are the things I've tried:
mysql -u root --password=mypass -e "show databases"
If ( $? ) {
echo "Hooray!"
} Else {
echo "Boo!"
}
This works correctly but doesn't suppress any output.
mysql -u root --password=mypass -e "show databases" > $null
Works correctly still but does not suppress the errors if the password is wrong.
mysql -u root --password=mypass -e "show databases" 2> $null
This does not work correctly. In this example, it always prints "Boo!"
mysql -u root --password=mypass -e "show databases" > $null 2>&1
This suppresses all output correctly but only ever prints "Boo!" like before.
Update:
The if ($LASTEXITCODE -eq 0) ... approach will continue to work robustly with external programs.
However, in PowerShell (Core) 7.2 and above, if ($?) ... works robustly too - see this answer for more information.
Use $LASTEXITCODE -eq 0 rather than $? to reliably detect a nonzero exit code (typically signaling failure) reported by an external program.
You can then use *> $null to categorically suppress all output without having to worry about the impact of that redirection on $?:
mysql -u root --password=mypass -e "show databases" *>$null
if ($LASTEXITCODE -eq 0) {
"Hooray!"
} else {
"Boo!"
}
Using a redirection that involves PowerShell's error stream - either explicitly via 2> or implicitly via *> - means that if any data is received via that stream - which in the case of calling an external program means any output from stderr - PowerShell sets $? to $false.
However, in the realm of external console / terminal programs, stderr isn't just used to output error information, but any information that isn't data, such as status information. Therefore, you cannot infer failure from the presence of stderr output.
External console / terminal programs communicate their success status solely via their exit code, which PowerShell reflects in the automatic $LASTEXITCODE variable.
It follows from the above that $? can be $false even if the exit code is 0, so it isn't a reliable success indicator - unlike $LASTEXITCODE.

Bash mysql error handling locked tables

i have a shell script that is called with a few parameters very frequently. it is supposed to build a query and execute the statement. in case an error occures, it should write the arguments seperated into a file so the error-handling can take place by calling that script again.
everything works but
the problem is, i catch connection refused error etc but if the statement cannot be executed because the table is locked and i do not want to wait for the timeout.
my code:
...
mysql -u ${username} -p${password} -h ${database} -P ${port} --connect-timeout=1 --skip-reconnect -e "$NQUERY"
mysqlstatus=$?
if [ $mysqlstatus -ne 0 ]; then
echo "[ERROR:QUERY COULD NOT BE EXECUTED:$mysqlstatus: QUERY WRITTEN TO LOG]" >> ${GENLOG}
#echo ${NQUERY} >> ${FQUER}
for i in "$#"; do
ARGS="$ARGS $i|"
done
echo "${ARGS}" >> ${ARGLOG}
else
echo "[OK] $NQUERY" >> ${GENLOG}
fi
...
but when a table is locked, the executing is not canceled and it runs like forever..
its not a solution for me to set the Max_statement_time_set or anything on the mysql server, since im not the only one using the db
You can use the timeout command along with mysql
timeout 3 mysql -u ...
This will wait 3 seconds for the mysql command to return, if the command runs longer then 3 seconds timeout will return exit status 124 to the shell. If you don't have timeout you can use job control with something like this.
#background the process
mysql -u ... &
#get pid of background process
bg_pid=$!
sleep 3
#check if your pid is still running
#using string matching incase pid was re assigned
if [[ $(ps -p $bg_pid -o args --no-headers) =~ "mysql" ]]
then
echo "running to long"
else
echo "OK"
fi

Template MySQL didn't get result in Zabbix

I'm planning to use Temple MySQL
to monitor MySQL detail instances. Unfortunatelly I can't get result. What am I still missing in configuration. Check it out zabbix-agent log those are piece of log not the whole log.
XECUTE_STR() command:'/usr/lib/zabbix/externalscripts/mysql_check.pl' len:0 cmd_result:''
28786:20160121:141008.072 Sending back []
28786:20160121:141008.072 listener #2 [waiting for connection]
28788:20160121:141008.648 In send_buffer() host:'127.0.0.1' port:10051 values:0/100
28788:20160121:141008.648 End of send_buffer():SUCCEED
28788:20160121:141008.648 active checks #1 [idle 1 sec]
28784:20160121:141008.795 collector [processing data]
28784:20160121:141008.796 In update_cpustats()
28784:20160121:141008.796 End of update_cpustats()
28784:20160121:141008.796 collector [idle 1 sec]
28785:20160121:141009.075 listener #1 [processing request]
28785:20160121:141009.075 Requested [mysql[root,Qwestions,lld]]
1. Add special user for MySQL:
example:
GRANT USAGE ON *.* TO 'zabbix'#'%' IDENTIFIED BY 'superpassword';
FLUSH PRIVILEGES;
2. Add user params into zabbix-agent configuration
Edit /etc/zabbix/zabbix_agentd.conf
UserParameter=mysql.version,mysql -V
UserParameter=mysql.status[*],echo "show global status where Variable_name='$1';" | HOME=/etc/zabbix mysql -N | awk '{print $$2}'
UserParameter=mysql.ping,HOME=/etc/zabbix mysqladmin ping | grep -c alive
# 'sum' on data_length or index_length alone needed when we are getting this information for whole database instead of a single table
UserParameter=mysql.size[*],echo "select sum($(case "$3" in both|"") echo "data_length+index_length";; data|index) echo "$3_length";; free) echo "data_free";; esac)) from information_schema.tables$([[ "$1" = "all" || ! "$1" ]] || echo " where table_schema='$1'")$([[ "$2" = "all" || ! "$2" ]] || echo "and table_name='$2'");" | HOME=/etc/zabbix mysql -N
if you want to extend monitoring items just add another UserParameter with proper SQL-query
3. Add auth-file for MySQL:
create .my.cnf file into /etc/zabbix/
[client]
user = zabbix
password = superpassword
4. Restart agent (and zabbix-proxy if you use it)
Log is useless. We see only script returns no result and can't see why.
Try to connect to MySQL from console using credentials that you provided in mysql_check.pl file. Be sure that user have enough permissions (SUPER at last).
mysql -hhostname -uuser -ppassword
Run script from user zabbix and check result:
perl ./mysql_check.pl

Write mysql error into a log file in bash

I'm writing a bash script and I want to redirect MySQL errors to a log file.
I had success with the below (ERROR 1045 (28000): Access denied for user... is being appended to the log file)
mysql -u user -pWrongpass -sN -e "query to update db;" 2>&1 | tee -a log
however, I'm not having success with this one. The error is displayed when I run the script but I don't see it in the log file.
result=$(mysql -u user -pWrongpass -sN "query to select from db;") 2>&1 | tee -a log
What's the correct syntax to put the result of a query into a variable while printing any potential error to the log file?
Thanks in advance and let me know if I'm not clear :)
You have to put the entire pipeline inside the command substitution.
result=$(mysql -u user -pWrongpass -sN "query to select from db;" 2>&1 |
tee -a log)
Since the output of mysql is piped to tee, it is the output of tee that you need to capture in result.

Linux Script & MySql operations not working, When Invoked from other script

I have written this piece of code to insert rows into table if not there, else, update the 'cnt' by one more. This works very well, when I invoke it from command line, when I invoke it from shell script, this does not work.
file=$1
echo "$0: Path to store $file" ;
res=`mysql -e "use spam_sending_scripts; select * from spamemailcount where path = '$file' limit 0,1"`
echo $res
if [ -z "$res" ]
then
mysql -e "use spam_sending_scripts; INSERT INTO spamemailcount (cnt,path) VALUES(1,'$file');"
echo "Inserting into DB $file , res $res" ;
exit ;
fi
mysql -e "use spam_sending_scripts; update spamemailcount SET cnt=cnt+1 where path = \"$file\"" ;
echo "Updating into DB $file" ;
#mysql -e "use spam_sending_scripts; select * from spamemailcount" >> /var/log/sendmail.log
mysql -e "use spam_sending_scripts; select * from spamemailcount"
root#server [/home]# insertintodb.sh AAA ==> This is working fine.
When I invoke from the other script, this file is executed, But Insert does not work.
I invoke it like: /home/insertintodb.sh $path
The $path variable is getting passed to insertintodb.sh correctly.
I am getting the following Error:
++ mysql -e 'use spam_sending_scripts; select * from spamemailcount where path = '\''hackerssquadron.com/wp-comments-post.php'\'' limit 0,1'
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: NO)
Use chmod command to make it executable
chmod ugo+x insertinodb.sh
Then try calling it same as #Jdamian suggested
bash -x /home/insertintodb.sh "$path"
This problem is solved.
When I try to invoke the script from the command line, It is working fine.
Reason => I am running this script as a root. So no problem
When I invoke the script using another shell script, It is not working.
Reason: This main script is being invoked by apache and It is trying to access the root DB, so permission denied.
Based on input from Skynet & Jdamian, I am able to debug it and resolve it.
Thank you very much for support, As usual this is one of the best place to get the technical queries resolved quickly by experts.