Create mysql database and user in bash script

后端 未结 4 1825
半阙折子戏
半阙折子戏 2020-12-23 16:52

This seems like it should be simple and I swear this code has worked for months but it\'s not working now. I\'m sure I\'m just overly tired but I would appreciate a knowing

4条回答
  •  隐瞒了意图╮
    2020-12-23 17:39

    This is what I use: https://raw.githubusercontent.com/saadismail/useful-bash-scripts/master/db.sh

    In your case you can use this:

    # create random password
    PASSWDDB="$(openssl rand -base64 12)"
    
    # replace "-" with "_" for database username
    MAINDB=${USER_NAME//[^a-zA-Z0-9]/_}
    
    # If /root/.my.cnf exists then it won't ask for root password
    if [ -f /root/.my.cnf ]; then
    
        mysql -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
        mysql -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
        mysql -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
        mysql -e "FLUSH PRIVILEGES;"
    
    # If /root/.my.cnf doesn't exist then it'll ask for root password   
    else
        echo "Please enter root user MySQL password!"
        echo "Note: password will be hidden when typing"
        read -sp rootpasswd
        mysql -uroot -p${rootpasswd} -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
        mysql -uroot -p${rootpasswd} -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
        mysql -uroot -p${rootpasswd} -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
        mysql -uroot -p${rootpasswd} -e "FLUSH PRIVILEGES;"
    fi
    

提交回复
热议问题