Automate a Backup with a Shell Script

Last modified by Eleni Cojocariu on 2026/08/19 20:22

Tutorial

This example turns Back Up an XWiki Instance into a single script a scheduler runs every night, for an instance served by Tomcat on a MariaDB database, and it stops the wiki for as long as the copy takes:

  1. Store the database credentials in the .my.cnf file of the account that will run the script, so that no password reaches the command line and the process list:
    [client]
    user=xwiki
    password=the password from hibernate.cfg.xml
  2. Save the script as /usr/local/bin/xwiki-backup:
    #!/bin/bash
    set -euo pipefail
    
    # Adapt these five values to your own installation.
    DATABASE=xwiki
    WEBAPP=/usr/lib/xwiki
    PERMANENT=/var/lib/xwiki/data
    DESTINATION=/srv/backup/xwiki
    SERVICE=tomcat10
    
    TARGET="$DESTINATION/$(date '+%Y-%m-%d')"
    mkdir -p "$TARGET"
    
    echo "Stopping $SERVICE"
    systemctl stop "$SERVICE"
    
    echo "Dumping the database"
    mysqldump --add-drop-database --databases "$DATABASE" | gzip > "$TARGET/database.sql.gz"
    
    echo "Copying the permanent directory, without its cache"
    tar -C "$(dirname "$PERMANENT")" -czf "$TARGET/permanent-directory.tar.gz" \
      --exclude=cache "$(basename "$PERMANENT")"
    
    echo "Copying the web application, configuration files and added jars included"
    tar -C "$(dirname "$WEBAPP")" -czf "$TARGET/webapp.tar.gz" "$(basename "$WEBAPP")"
    
    echo "Starting $SERVICE"
    systemctl start "$SERVICE"
    
    echo "Backup written to $TARGET"
  3. Make the script executable:
    chmod +x /usr/local/bin/xwiki-backup
  4. Run it once by hand and read what it prints, since a failing step stops it before it can report a backup it did not take.
  5. Schedule it, for example every night at 3 o'clock, from the crontab of the account that owns the .my.cnf file:
    0 3 * * * /usr/local/bin/xwiki-backup
  6. Confirm the next morning that the night's run produced its own dated directory:
    $ ls -1 /srv/backup/xwiki/2026-08-19/
    database.sql.gz
    permanent-directory.tar.gz
    webapp.tar.gz

FAQ

How do I keep the disk from filling up?

Add a step that deletes the dated directories older than the retention you want to keep, with a find command on the destination directory.

The instance uses PostgreSQL. What changes?

The dump line, which becomes the PostgreSQL one from Database Backup and Restore Commands, and the credentials, which move to that client's own configuration file.

Related

Get Connected