mysql批量建库及用户

1、配置数据库连接信息 config.ini

[client]
host="10.*.*.*"
port=3306
user="root"
password="123456"

2、设置需要创建数据库及用户信息变量

export MYSQL_DATABASE=datbase01,datbase02,datbase03
export MYSQL_USER=user01,user02,user03
export MYSQL_PASSWORD=passd01,passd02,passd03

3、执行批量脚本

#!/bin/bash
# Date:2021-01-12  
# Author: Create by cooper_73

check_config(){
  ch_m=`mysqladmin --defaults-extra-file=./config.ini ping`
  if [ "$ch_m" = "mysqld is alive" ];then
        con_res="ok"
    else
        echo  -e "--> MySql can not connected, Please check ./config.ini or mysql server!"
        exit 0
  fi
}

check_env(){
  if [ ! $MYSQL_DATABASE ] || [ ! $MYSQL_USER ] || [ ! $MYSQL_PASSWORD ]; then
   echo -e "\n*** Place check The environment variable whith a null:***\n---> MYSQL_DATABASE=$MYSQL_DATABASE\n---> MYSQL_USER=$MYSQL_USER\n---> MYSQL_PASSWORD=$MYSQL_PASSWORD \n"
   exit 0
  elif [ ${#MYSQL_USER_ARRAY[@]} == ${#MYSQL_DATABASE_ARRAY[@]} ] && [ ${#MYSQL_USER_ARRAY[@]} == ${#MYSQL_PASSWORD_ARRAY[@]} ];then
   env_res="ok"
  else
   echo -e "\n*** The environment variable‘s number is not correct: ***\n---> MYSQL_DATABASE:${#MYSQL_DATABASE_ARRAY[@]} \n---> MYSQL_USER:${#MYSQL_USER_ARRAY[@]}\n---> MYSQL_PASSWORD:${#MYSQL_PASSWORD_ARRAY[@]} \n"
   exit 0
  fi
}

mysql_active(){
  mysql --defaults-extra-file=./config.ini  "$@"
}

e_info(){
  if [ $? -eq 0 ]; then
     echo -e "==>> Execute Successfully! \n" 
  else
     echo -e "[[error]]: Sorry, Sql Execution Failured!\n"
  fi
}

check_config
check_env

IFS=, read -r -a MYSQL_DATABASE_ARRAY <<< $MYSQL_DATABASE
IFS=, read -r -a MYSQL_USER_ARRAY <<< $MYSQL_USER
IFS=, read -r -a MYSQL_PASSWORD_ARRAY <<< $MYSQL_PASSWORD

for index in ${!MYSQL_USER_ARRAY[@]}
    do
        DATABASE=${MYSQL_DATABASE_ARRAY[index]}
        USER=${MYSQL_USER_ARRAY[index]}
        PASSWORD=${MYSQL_PASSWORD_ARRAY[index]}

        echo  "Creating database ${DATABASE} ..."
                mysql_active  --database=mysql  -e "CREATE DATABASE IF NOT EXISTS \`$DATABASE\` ;"
                e_info

        echo "Creating user ${USER} ..."
                mysql_active  --database=mysql  -e "CREATE USER  IF NOT EXISTS ‘$USER‘@‘%‘ IDENTIFIED BY ‘$PASSWORD‘ ;"
                e_info

        echo "Giving user ${USER} access to schema ${DATABASE} ..."
                mysql_active  --database=mysql  -e "GRANT ALL ON \`${DATABASE//_/\\_}\`.* TO ‘$USER‘@‘%‘ ;"
                e_info

                mysql_active --database=mysql <<<"FLUSH PRIVILEGES ;"
        
    done

echo -e "\n *** MySql Initialization is complete *** \n"

 

mysql批量建库及用户

上一篇:classfile解析的内容


下一篇:数据库索引和ArcGIS空间索引一样吗?