Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,14 @@ Make it executable before scheduling it with `cron`:
```bash
chmod +x scripts/backup_mongodb.sh
```
Store `DBNAME` (and optional credentials) in environment variables rather than
editing the script. You may create a file named `~/.mongodb_backup_env` with
content like:

```bash
export DBNAME="fmriprep_stats"
# export MONGO_USER=myuser
# export MONGO_PASS=mypassword
```

The backup script will source this file if present.
28 changes: 23 additions & 5 deletions scripts/backup_mongodb.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@
# scripts/backup_mongodb.sh
# Backup MongoDB database, ensuring mongod is running.

set -euo pipefail

# Optionally source credentials from ~/.mongodb_backup_env
ENV_FILE="$HOME/.mongodb_backup_env"
if [ -f "$ENV_FILE" ]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
fi

# DBNAME is required; credentials are optional
: "${DBNAME:?Set DBNAME, e.g., export DBNAME=your_db}"

DATE=$(date +%Y-%m-%d)
BACKUP_DIR="$HOME/Dropbox/backups"
DBNAME="DBNAME"
USERNAME="USERNAME"
PASSWORD="PASSWORD"
BACKUP_DIR="$HOME/Dropbox/fmriprep_stats"
BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}"

mkdir -p "$BACKUP_DIR"
Expand All @@ -27,8 +36,17 @@ else
started_mongod=true
fi

# Build mongodump options
dump_opts=(--db "$DBNAME" --out "$BACKUP_PATH")
if [ -n "${MONGO_USER:-}" ]; then
dump_opts+=(--username "$MONGO_USER")
fi
if [ -n "${MONGO_PASS:-}" ]; then
dump_opts+=(--password "$MONGO_PASS")
fi

# Dump the database
mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH"
mongodump "${dump_opts[@]}"

# Stop mongod if we started it
if [ "$started_mongod" = true ]; then
Expand Down