Skip to content

Instantly share code, notes, and snippets.

@clockworkgeek
Created December 15, 2015 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clockworkgeek/e2cec63c1fafb43a371b to your computer and use it in GitHub Desktop.
Save clockworkgeek/e2cec63c1fafb43a371b to your computer and use it in GitHub Desktop.
Read Magento connection settings from local.xml and backup database
#!/bin/sh
##
## save to "shell" dir and call every few hours from cron
##
## find root dir of Magento site, do not rely on current dir
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DIR=$(dirname $DIR)
LOCAL_XML=$DIR/app/etc/local.xml
## because xmllint doesn't parse CDATA tag for us
function value {
if [[ $@ =~ ^\<!\[CDATA\[(.+)\]\]\>$ ]]
then
echo ${BASH_REMATCH[1]}
else
echo $@
fi
}
## xmllint is part of libxml which is very widespread and has good XPath implementation
DB_HOST=$(value $(xmllint --xpath '/config/global/resources/default_setup/connection/host/text()' $LOCAL_XML))
DB_NAME=$(value $(xmllint --xpath '/config/global/resources/default_setup/connection/dbname/text()' $LOCAL_XML))
DB_USER=$(value $(xmllint --xpath '/config/global/resources/default_setup/connection/username/text()' $LOCAL_XML))
DB_PASS=$(value $(xmllint --xpath '/config/global/resources/default_setup/connection/password/text()' $LOCAL_XML))
## create simple backup dir and file
mkdir -p "$DIR/var/backups"
DATE=$(date '+%Y-%d-%m_%H-%M')
mysqldump -u "$DB_USER" "-p$DB_PASS" -h "$DB_HOST" "$DB_NAME" | gzip > "$DIR/var/backups/database_$DATE.sql.gz"
## delete backups two whole days past or older
find $DIR/var/backups/database* -mtime +1 -delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment