diff --git a/docs/Bash.md b/docs/Bash.md index 0cbcc50..a6ecea2 100644 --- a/docs/Bash.md +++ b/docs/Bash.md @@ -100,6 +100,10 @@ Create an SSH key and uploads it to the given host. Upload current directory to special directory on my hosting. +### mysql-dump [mysql_username] [mysql_host] + +Backup remote MySQL database to `~/Backups/hostname/dbname_YYYY-MM-DD.sql.gz`. + ## NPM diff --git a/includes/bash_functions.bash b/includes/bash_functions.bash index 1446c5b..745d95f 100644 --- a/includes/bash_functions.bash +++ b/includes/bash_functions.bash @@ -70,9 +70,11 @@ function nyan() { echo -en $RED'-_-_-_-_-_-_-_' echo -e $NOCOLOR$BOLD',------,'$NOCOLOR echo -en $YELLOW'_-_-_-_-_-_-_-' + echo -e $NOCOLOR$BOLD'| /\_/\\'$NOCOLOR echo -en $GREEN'-_-_-_-_-_-_-' echo -e $NOCOLOR$BOLD'~|__( ^ .^)'$NOCOLOR echo -en $CYAN'-_-_-_-_-_-_-' + echo -e $NOCOLOR$BOLD'"" ""'$NOCOLOR echo } @@ -176,3 +178,49 @@ function crlf() { grep -q $'\x0D' "$file" && echo "$file" && [ $force ] && dos2unix "$file" done } + +# Backup remote MySQL database to ~/Backups/hostname/dbname_YYYY-MM-DD.sql.gz +# USAGE: mysql-dump [mysql_username] [mysql_host] +mysql-dump() { + local ssh_hostname=$1 + local mysql_database=$2 + local mysql_username=$3 + local mysql_host=$4 + local location="$HOME/Backups" + local suffix=$(date +'%Y-%m-%d') + + if [[ $ssh_hostname == "" ]] || [[ $mysql_database == "" ]]; then + echo "Usage: mysql-dump [mysql_username] [mysql_host]" + else + header "Backing up $mysql_database@$ssh_hostname..." + + if [[ $mysql_username != "" ]]; then + mysql_username="-u $mysql_username -p " + fi + + if [[ $mysql_host != "" ]]; then + mysql_host=" -h $mysql_host" + fi + + # Ensure backup directory + local backup_dir="$location/$ssh_hostname" + mkdir -p $backup_dir + + # Give the user a warning if the file already exists + local basename=$mysql_database"_"$suffix + local local_filepath="$backup_dir/$basename.sql.gz" + if [ -f "$local_filepath" ]; then + echo -e $RED"WARNING: Backup file '$local_filepath' already exists.$NOCOLOR\nOwerwrite? (Y/N)" + read proceed + + if [[ $proceed != "y" ]]; then + return + fi + fi + + ssh -C $ssh_hostname "mysqldump --opt --compress $mysql_username$mysql_database$mysql_host | gzip -c" > "$local_filepath" + + echo + echo "Done: $local_filepath" + fi +}