Skip to content

Instantly share code, notes, and snippets.

@cwood
Created July 30, 2014 14:46
Show Gist options
  • Select an option

  • Save cwood/75a2e842f450807647d2 to your computer and use it in GitHub Desktop.

Select an option

Save cwood/75a2e842f450807647d2 to your computer and use it in GitHub Desktop.

Revisions

  1. cwood created this gist Jul 30, 2014.
    48 changes: 48 additions & 0 deletions clone-mysql-database
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    #!/usr/bin/env zsh

    autoload -U colors

    if [[ -z $1 ]]; then
    read "database_name?Databse Name: "
    else
    database_name=$1
    fi

    if [[ -z $2 ]]; then
    read "database_user?Database Username: "
    else
    database_user=$2
    fi

    if [[ -z $3 ]]; then
    read "database_admin?Database Admin: "
    else
    database_admin=$3
    fi

    if [[ -z $4 ]]; then
    read -s "database_admin_password?Database Admin Password: "
    else
    database_admin_password=$4
    fi

    echo

    db_clone="${database_name}_${RANDOM}"
    mysqladmin create $db_clone -u $database_admin -p$database_admin_password

    if [[ $? == 0 ]]; then
    echo "GRANT ALL PRIVILEGES ON ${db_clone}.* TO '${database_user}'@'localhost';" | \
    mysql -u $database_admin -p$database_admin_password

    if [[ $? == 0 ]]; then
    mysqldump -u $database_admin -p$database_admin_password $database_name | \
    mysql -u $database_admin -p$database_admin_password $db_clone
    echo "${fg[green]}Your new database clone is ${db_clone}${color_reset}"
    else
    mysqladmin -f drop $db_clone -u $database_admin -p$database_admin_password
    echo "${fg[red]}Failed to set privilages on db${color_reset}"
    fi
    else
    echo "${fg[red]}Failed to create db${color_reset}"
    fi