Shell and MySQL custom connection success message - mysql

How can I print a custom success message if connected to mysql via shell? Instead of displaying mysql error messages.
Something like this
if [ "$mysql_connected" ]; then
echo "connected"
# do mysql stuff
else
echo "connection failed"
fi
Thanks in advance!

Use exit status as shown below:
mysql -uroot -pabc -e"show databases;"
if [ $? -eq 0 ];then
echo "success";
else
echo "failed to connect";
fi

Related

BASH: Bakup MySQL database and send via FTP to remote server

I trying to create BASH script for my API server where I do daily backup with cron. Here is my script:
#!/bin/bash
################################################################
##
## MySQL Database Backup Script
## Written By: Ivijan-Stefan Stipic
## URL: https://infinitumform.com
## Last Update: Jul 08, 2019
##
################################################################
export PATH=/bin:/usr/bin:/usr/local/bin
#################################################################
# Today date
TODAY=`date +"%d%b%Y"`
# Database
DATABASE_NAME='some_database_name'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='some_username'
MYSQL_PASSWORD='pa55W0r6'
# FTP
FTP_HOST='https://someremote.host'
FTP_USER='ftp-username'
FTP_PASSWORD='ftp-p#55w0r6'
FTP_PATH='/backup'
# Backup location
DB_BACKUP_PATH='/root/backups'
# Filename setup
FILE_NAME=${DATABASE_NAME} ## We can change this to some other name
FILE_NAME_PREFIX='' ## prefix in the file
FILE_NAME_SUFFIX='' ## suffix in the file
## Number of days to keep local backup copy
BACKUP_RETAIN_DAYS=15
# Full file path
FILE=${DB_BACKUP_PATH}/${TODAY}/${FILE_NAME_PREFIX}${FILE_NAME}${FILE_NAME_SUFFIX}-${TODAY}.sql.gz
#################################################################
if [ ! -z ${DATABASE_NAME} ]; then
mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "Backup started for database - ${DATABASE_NAME}"
mysqldump --host=${MYSQL_HOST} --port=${MYSQL_PORT} --databases ${DATABASE_NAME} --add-drop-database --triggers --routines --events --password=${MYSQL_PASSWORD} --user=${MYSQL_USER} --single-transaction | gzip > ${FILE}
if [ $? -eq 0 ]; then
echo "Database backup successfully completed"
else
echo "Error found during backup"
fi
else
echo "ERROR: Datbase not defined"
fi
##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
if [ ! -z ${DB_BACKUP_PATH} ]; then
cd ${DB_BACKUP_PATH}
if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
rm -rf ${DBDELDATE}
echo "Old backups cleaned up"
fi
fi
#### Send backup via FTP ####
if [ ! -z ${FTP_USER} ]; then
echo "Sending bakup files to ${FTP_HOST} via FTP"
curl -T "${FILE}" -u ${FTP_USER}:${FTP_PASSWORD} ${FTP_HOST}${FTP_PATH}
if [ $? -eq 0 ]; then
echo "Files successfuly sent via FTP to remote bakup server"
else
echo "FTP error. Files was not sent properly."
fi
fi
### End of script ####
In my office I have server where I keep backups and want to automate this script to send via FTP files from API server to my office server after backup is done.
I try to use cURL to send files but this fail.
...
#### Send backup via FTP ####
if [ ! -z ${FTP_USER} ]; then
echo "Sending bakup files to ${FTP_HOST} via FTP"
curl -T "${FILE}" -u ${FTP_USER}:${FTP_PASSWORD} ${FTP_HOST}${FTP_PATH}
if [ $? -eq 0 ]; then
echo "Files successfuly sent via FTP to remote bakup server"
else
echo "FTP error. Files was not sent properly."
fi
fi
...
Is there some good and safe way to do this?
You can use ncftpput.
See my simple script about it, here: https://github.com/NabiKAZ/MySQL-Backup

How to run a MySQL procedure from a Linux shell script and store its output in a file

I have a mysql procedure which I want to run from a shell script in linux and store the output in a log file. But my script is not working. Below is my script:
#!/bin/bash
source CX20-PIM-properties.prop
status=$(mysql -u $user -h $host -D $database -se "call fetchFromPAsIsToPIDX()")
if [ $status ]; then
echo "Procedure executed successfully" | tee procedure_output.log
else
echo "Procedure execution failed" | tee procedure_output.log
fi
And the output is below:
[anurag#pimdev0 ~]$ ./load-from-AsIs-to-IDX.sh
Procedure execution failed
You should store the return value of cmd in status not stdout of cmd.
#!/bin/bash
source CX20-PIM-properties.prop
if [ `mysql -u $user -h $host -D $database -se "call fetchFromPAsIsToPIDX()" &> /dev/null` ]; then
echo "Procedure executed successfully" | tee procedure_output.log
else
echo "Procedure execution failed" | tee procedure_output.log
fi

Bash: testing if executed command was succesfull

I have the following script:
if [ `mysql -u root -p < test.sql` ]; then
echo "success"
else
echo "some error"
fi
How can I check in the if if the command went well or there was some sql error?
You don't need the test command, i.e. [ here.
Assuming that mysql produces a non-zero exit code in case of failure and 0 on success, then you can say:
if mysql -u root -p < test.sql; then
echo "success"
else
echo "some error"
fi
Another way this is typically done is with the "&&" and "||" separators. For example:
mysql -u root -p < test.sql && echo "success" || echo "some error"
If the mysql command exits with status 0, then "success" will be printed. If it doesn't, "some error" will be printed.

syntax error near unexpected token `done' in bash code

I am looking for some working shell code for auto restart mysql servers if it is not working. here are some code witch i foound in google search, listen 3306 port, if it is not working, restart. if can not restart, reboot the server.
Can this code work? If not, is anyone can share me a working code? If yes, i met syntax error near unexpected tokendone' in bash code`, how to solve it? thanks.
PORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'`
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
if [ "$PORT" == "3306" ];then
echo "mysql is running......"
else
service mysql restart
if [ "$PORT" == "3306" ];then
else
reboot
fi
fi
break
done
Modify code:
PORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'`
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
if [ "$PORT" == "3306" ];then
echo "mysql is running......"
else
service mysql restart
if [ "$PORT" == "3306" ];then
:
else
reboot
fi
fi
break
done
Your condition test must execute some sort of code if true.
It looks like you want to reboot if "$PORT" is not "3306".
You should only use break when testing a condition, otherwise the loop will only execute once.
The PORT variable will not update unless you call the code that sets it again after you need it to update.
Also, you don't need to use grep when you are using awk.
#!/bin/bash
callport ()
{
PORT=`netstat -na|awk -F[:" "]+ '/LISTEN/ && /3306/ {print $5}'`
}
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
callport
if [ "$PORT" == "3306" ];then
echo "mysql is running......"
break
else
service mysql restart
callport
if [ "$PORT" != "3306" ];then
reboot
fi
fi
done

Using rsnapshot and mysqldump to backup remote mySQL Databases

I am using rsnapshot to backup our remote servers and I need to add MySQL backups.
rsnapshot calls a remote script that dumps the mysql DB's on the server. The problem is, the script does not exclude the information_schema database and therefore it dies )or appears to die and I have a second problem.)
I'm not sure how I would exclude the information_schema DB from this script:
### SETUP MYSQL LOGIN ###
MUSER='USER'
MPASS='PASSWORD'
MHOST="127.0.0.1"
### Set to 1 if you need to see progress while dumping dbs ###
VERBOSE=0
### Set bins path ###
GZIP=/bin/gzip
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump
RM=/bin/rm
MKDIR=/bin/mkdir
MYSQLADMIN=/usr/bin/mysqladmin
GREP=/bin/grep
### Setup dump directory ###
BAKRSNROOT=/tmp/rsnapshot/mysql
#####################################
### ----[ No Editing below ]------###
#####################################
### Default time format ###
TIME_FORMAT='%H_%M_%S%P'
### Make a backup ###
backup_mysql_rsnapshot(){
local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
local db="";
[ ! -d $BAKRSNROOT ] && ${MKDIR} -p $BAKRSNROOT
${RM} -f $BAKRSNROOT/* >/dev/null 2>&1
[ $VERBOSE -eq 1 ] && echo "*** Dumping MySQL Database ***"
[ $VERBOSE -eq 1 ] && echo -n "Database> "
for db in $DBS
do
local tTime=$(date +"${TIME_FORMAT}")
local FILE="${BAKRSNROOT}/${db}.${tTime}.gz"
[ $VERBOSE -eq 1 ] && echo -n "$db.."
${MYSQLDUMP} -u ${MUSER} -h ${MHOST} -p${MPASS} $db | ${GZIP} -9 > $FILE
done
[ $VERBOSE -eq 1 ] && echo ""
[ $VERBOSE -eq 1 ] && echo "*** Backup done [ files wrote to $BAKRSNROOT] ***"
}
### Die on demand with message ###
die(){
echo "$#"
exit 999
}
### Make sure bins exists.. else die
verify_bins(){
[ ! -x $GZIP ] && die "File $GZIP does not exists. Make sure correct path is set in $0."
[ ! -x $MYSQL ] && die "File $MYSQL does not exists. Make sure correct path is set in $0."
[ ! -x $MYSQLDUMP ] && die "File $MYSQLDUMP does not exists. Make sure correct path is set in $0."
[ ! -x $RM ] && die "File $RM does not exists. Make sure correct path is set in $0."
[ ! -x $MKDIR ] && die "File $MKDIR does not exists. Make sure correct path is set in $0."
[ ! -x $MYSQLADMIN ] && die "File $MYSQLADMIN does not exists. Make sure correct path is set in $0."
[ ! -x $GREP ] && die "File $GREP does not exists. Make sure correct path is set in $0."
}
### Make sure we can connect to server ... else die
verify_mysql_connection(){
$MYSQLADMIN -u $MUSER -h $MHOST -p$MPASS ping | $GREP 'alive'>/dev/null
[ $? -eq 0 ] || die "Error: Cannot connect to MySQL Server. Make sure username and password are set correctly in $0"
}
### main ####
verify_bins
verify_mysql_connection
backup_mysql_rsnapshot
Look into mysqldump and its --all-databases parameter. Don't reinvent the wheel!
mysqldump does not dump theINFORMATION_SCHEMA database. If you name that database explicitly on the command line,mysqldump silently ignores it.
If you have a version of mysqldump that does really not exclude INFORMATION_SCHEMA and you need all DBs in seperate files, just exclude it from your loop:
for db in $DBS
do
if [ $db -ne "INFORMATION_SCHEMA" ] ; do
YOUR_STUFF()
done
dome
Replace the following line:
local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
with
local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases' -s --skip-column-names|grep -vi information_schema)"