Export database query results through the Shell to Excel, and send messages to the mailbox #!/bin/bash# through the shell to query the data information and save in Excel, and record the log #data:2018-06-14#name:zhang# Database connection address dbserver= ' 192.168.1.1 ' #数据库用户名DBUserName = ' zhang ' #数据库密码DBPasswd = ' Zhang ' ################################## ######################### #选择数据库Use_Cmd = "Use zhang" #查询数据库信息Sql语Select_Cmd = "select * from STUDENTS; " ########################################################### #后台支付信息保存路径Payment_DataDir = '/opt/select_back ' # Log save path logdir=/opt/select_back/logs# data export time backtime= ' date +%y%m%d%h%m ' #保存文件名称DataName = "Payment order Information" ############# ############################################## #邮件收件人 #email_receiver_people= "[email protected]" #邮件主题 #email _subject= "More information $backtime" ######################################################### #MKDIR = '/bin/mkdir ' ########## ############################################## #echo "################# #判断备份路径 ###################### ####### "test ! -d $Payment _datadir && $MKDIR -p $Payment _ datadirtest ! -w $Payment _datadir && echo "error: $Payment _datadir is Un-writeable. " && exit 0test ! -d $LogDir && $MKDIR -p $LogDirtest ! -w $LogDir && echo "error: $LogDir is un-writeable. " && exit 0echo "##################### #备份开始 #############################" Echo " >> $LogDir/$DataName .logecho -e " \033[44; 32m-------------------------Split Line-----------------------\033[0m \n " >> $LogDir/$ dataname.logecho "Export time is $backtime, export ${dataname} file Start" >> $LogDir/$DataName. log/usr/local/ mysql/bin/mysql -u$dbusername -h$dbserver -p$dbpasswd -e "$Use _cmd; $Select _cmd" > $Payment _datadir/$DataName-$backtime .xls#sed -i ' s/^/' &/g ' $Payment _datadir /$DataName-$backtime. xls# Use the Iconv conversion encoding format to convert the LINux UTF8 converted to Windows gbkiconv -f "Utf-8" -t "GBK" $Payment _datadir/$DataName-$ backtime.xls > $Payment _datadir/orders.xls# because the first column of data is more than 18 bits, the scientific notation is used in Excel, so the first column is added "'" to the text format sed -i ' s/^/' &/g ' $Payment _datadir/orders.xlsif [ "$?" == 0 ];then# export results via mail script, send to mailbox/opt/py3/bin/python3 /opt/select_back/select_mail.pyecho "Export time is $backtime, export $dataname file end!!! " >> $LogDir/$DataName .logecho " mysql-$DataName data export success!!! " >> $LogDir/$DataName .logelseecho " Export time is $backtime, export $dataname file end!!! " >> $LogDir/$DataName .logecho " mysql-$DataName data guide failed!!! " >> $LogDir/$DataName .logfiecho " ##################### #导出数据结束, Time: $backtime ##### "
Note: Please correct me if there are any errors or deficiencies in these areas.
Export database query results to excel through the shell and send them to the mailbox by mail