shell脚本连接mysql,执行sql导出文件

#!/bin/bash

source /etc/profile

source ~/.bash_profile

set -o nounset

set -o errexit

#Author: gupx

#Time: 2021-07-02 13:00:00

#Name: test.sh

#Description: shell脚本连接mysql

useage(){

echo "useage: ./test.sh M/D"

echo "example: ./test M/D"

}

log(){

now_time=\'[\'$(date +"%Y-%m-%d %H:%M:%S")\']\'

echo ${now_time} $1 | tee -a ${log_file}

}

#导出文本路径

file_path_table="/usr/tmp/test/"

#mysql相关变量

STNAME="xx.xx.xx.xxx"

PORT="xxxx"

USERNAME="test"

PASSWORD="123456"

DBNAME="TEST_DB"

use_db_sql="use ${DBNAME}"

test_table_sql="select * from test_table;"

test_table1_sql="select * from test_table1;"

#连接mysql

exec_files(){

exec_sql=$1;

file_name=`echo $exec_sql | grep -Po \'(?<=from ).*(?=;)\'`

exec_result=`mysql -h${STNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${exec_sql}"`

echo "${exec_result}" | sed \'s/\t/|/g\' > ${file_path_table}${file_name}_${day_date}.txt

}

main(){

exec_files "$test_table_sql";

}

main;