MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the original script you will find an explanation of each line, the setup it needs, an improved version that checks whether the backup actually worked, and steps to schedule it with cron.


Write a Shell Bash Script for backup a local file into a remote server



How the example script works

The script above does two things. It uses rsync over SSH to copy /path/to/yourfile into the /backup/ directory on backupserver.com. Then it pipes a one-line message into mail to send a "backup complete" email.

PartMeaning
-aArchive mode. Copies recursively and keeps permissions, timestamps, symlinks, owner and group (owner and group are only kept when the receiving side runs as root).
-vVerbose. Lists each file as it is transferred.
-zCompresses data in transit. Helps on slow links but costs CPU on fast LANs.
-e "ssh "Sets SSH as the remote shell. Current rsync versions already use SSH by default, so this option only matters when you want to add SSH options such as a key file or port.
user@backupserver.com:/backup/The destination: remote user, host and directory, separated by @ and :.
$(date)Command substitution that puts the current date and time into the email body.

Note: rsync only copies what has changed. When you run the script again, files that are already up to date on the server are skipped, so repeat runs finish quickly.

Prerequisites

  • rsync installed on both the local machine and the backup server (sudo apt install rsync or sudo dnf install rsync).
  • SSH access to the backup server, using a key with no password prompt so the script can run unattended.
  • A mail command: mailutils on Debian/Ubuntu, or s-nail/mailx on RHEL-family systems. You also need a working mail transfer agent such as Postfix, or a relay that is already set up. Without one, mail can exit cleanly and still deliver nothing.
  • Write permission on the remote backup directory for the SSH user.

Set up a dedicated SSH key for backups and test that it logs in without a prompt:

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_backup -N "" -C "backup key"
ssh-copy-id -i ~/.ssh/id_ed25519_backup.pub user@backupserver.example.com

# Must print OK without asking for a password
ssh -i ~/.ssh/id_ed25519_backup -o BatchMode=yes user@backupserver.example.com 'echo OK'Code language: PHP (php)

Note: Run that first SSH login by hand. It stores the server's host key in ~/.ssh/known_hosts. If you skip it, an unattended run fails with Host key verification failed.

Problems with the original script

  • The email is always sent. The script never checks whether rsync succeeded, so a failed transfer still sends "backup complete". That is worse than sending nothing.
  • Paths and addresses are hard-coded. To back up a different file, you have to edit the script.
  • There is no check that the source exists, and the remote directory is assumed to exist already.
  • Nothing records what happened. The rsync output goes to the terminal, or is lost when cron runs the script, and the email body holds only a date.
  • The script always exits with code 0 because the last command is mail. Cron and monitoring tools cannot see that the backup failed.

Improved backup script

This version takes the source path as an argument. It creates the remote directory, saves the rsync output, puts the result in the email subject and exits with a non-zero code on failure.

#!/usr/bin/env bash
# remotebackup.sh - copy a local file or directory to a remote server over SSH
set -euo pipefail

SRC="${1:?Usage: $0 /path/to/file-or-dir}"
DEST_USER="user"
DEST_HOST="backupserver.example.com"
DEST_DIR="/backup/$(hostname -s)"
SSH_KEY="$HOME/.ssh/id_ed25519_backup"
MAIL_TO="user@example.com"
SSH_OPTS=(-i "$SSH_KEY" -o BatchMode=yes -o ConnectTimeout=10)

LOG="$(mktemp)"
trap 'rm -f "$LOG"' EXIT

if [[ ! -e "$SRC" ]]; then
  echo "ERROR: source '$SRC' does not exist" >&2
  exit 1
fi

START="$(date '+%F %T')"

if ssh "${SSH_OPTS[@]}" "$DEST_USER@$DEST_HOST" "mkdir -p '$DEST_DIR'" >>"$LOG" 2>&1 &&
   rsync -az --stats -e "ssh ${SSH_OPTS[*]}" \
     "$SRC" "$DEST_USER@$DEST_HOST:$DEST_DIR/" >>"$LOG" 2>&1; then
  RC=0
  STATUS="SUCCESS"
else
  RC=$?
  STATUS="FAILED (exit code $RC)"
fi

{
  echo "Backup of $SRC on $(hostname) started $START"
  echo "Destination: $DEST_USER@$DEST_HOST:$DEST_DIR/"
  echo "Result: $STATUS"
  echo
  cat "$LOG"
} | mail -s "Backup $STATUS: $(hostname -s) $SRC" "$MAIL_TO"

echo "Backup $STATUS"
exit "$RC"Code language: PHP (php)
  • set -euo pipefail stops the script on unexpected errors and unset variables. Commands used as an if condition do not trigger -e, so the script can still report a failure.
  • ${1:?...} stops with a usage message when no path is given.
  • BatchMode=yes makes SSH fail at once instead of waiting for a password that nobody will type. ConnectTimeout=10 stops the script from hanging on a host that cannot be reached.
  • In the else branch, $? holds the exit code of the failed condition: 255 for SSH errors, or an rsync code such as 23 (partial transfer).
  • trap ... EXIT deletes the temporary log however the script ends.
  • The key path is expanded into the -e string, so it must not contain spaces.

Run and verify the backup

  1. Make the script executable: chmod +x remotebackup.sh.
  2. Do a dry run first by temporarily adding -n (--dry-run) to the rsync options. rsync reports what it would send but transfers nothing.
  3. Run it for real: ./remotebackup.sh /etc/hosts. A successful run prints Backup SUCCESS.
  4. Check the exit code: echo $? should print 0.
  5. Confirm the file reached the server: ssh -i ~/.ssh/id_ed25519_backup user@backupserver.example.com 'ls -l /backup/$(hostname -s)/'. Use single quotes so $(hostname -s) runs on the server. If your backup server has a different short hostname, type the folder name instead.

Trailing slashes change what rsync copies. rsync -a /data dest:/backup/ creates /backup/data/. rsync -a /data/ dest:/backup/ copies the contents of /data straight into /backup/.

Schedule it with cron

Open your crontab with crontab -e and add a line. Cron runs with a minimal environment, so use absolute paths everywhere:

# Every day at 02:30
30 2 * * * /usr/local/bin/remotebackup.sh /home/app/data >> /home/app/remotebackup-cron.log 2>&1Code language: PHP (php)

Run the job as the same user that owns the SSH key and known_hosts entry. Otherwise SSH looks in another home directory and authentication fails.

Common errors and fixes

ErrorCauseFix
Permission denied (publickey)The key is not in the remote authorized_keys, or the wrong key or user is in use.Run ssh-copy-id again and check the -i path and the remote user name.
Host key verification failedThe server's host key is not in known_hosts for the user running the script.Connect once by hand as that user, or add the key with ssh-keyscan after checking its fingerprint.
rsync: command not found (remote side)rsync is not installed on the backup server.Install rsync on the server.
mail: command not foundNo mail client is installed.Install mailutils or s-nail.
Script succeeds but no email arrivesNo MTA or relay is set up, or the message was marked as spam.Set up Postfix or a relay, and check the local mail log.
rsync exit code 23Some files could not be read, usually because of permissions.Check the rsync output in the email for the files involved and fix their permissions.

Restoring and making backups safer

To restore, run rsync with the source and destination swapped:

rsync -av -e "ssh -i $HOME/.ssh/id_ed25519_backup" \
  user@backupserver.example.com:/backup/myhost/yourfile /tmp/restore/Code language: JavaScript (javascript)
  • This script keeps only one copy, which is overwritten on every run. If a file becomes corrupted, the bad version replaces the good one at the next run. For history, write each run to a dated directory such as $DEST_DIR/$(date +%F)/, or use --link-dest so unchanged files are stored as hard links.
  • Use a dedicated, unprivileged backup user on the server. Do not log in as root.
  • Protect the private key with chmod 600. On the server you can limit the key to rsync with a command= restriction in authorized_keys, for example with the rrsync helper that some rsync packages include.
  • Do not add --delete unless you mean it. It removes files from the backup when they are deleted locally.
  • Test a restore regularly. A backup you have never restored from is unproven.

For more practice, see the other exercises in More Shell Scripting tutorials, and try moving the email logic into a reusable function with the help of Shell Scripting Tutorials: Function.

Frequently asked questions

What is the difference between rsync and scp for backups?

scp copies every file in full each time. rsync compares source and destination and sends only what has changed, and it can resume and keep file metadata. That makes rsync better for repeated backups.

How do I run an rsync backup over SSH without typing a password?

Create an SSH key pair with ssh-keygen and install the public key on the server with ssh-copy-id. Then point rsync at the key with -e "ssh -i ~/.ssh/keyfile".

Does rsync delete files on the backup server?

Not by default. Files are deleted on the destination only when you add --delete or one of the related options.

Why does my backup script work by hand but fail in cron?

Cron uses a minimal environment with a short PATH, and it may run as a different user. Use absolute paths, run the job as the user who owns the SSH key, and redirect output to a log file so you can see the error.

How can I tell if the rsync backup failed?

Check rsync's exit code: 0 means success and any other value means failure, with 255 meaning an SSH error. The improved script puts this code in the email subject and also returns it as its own exit code.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Shell Bash Scripting: Assignment & Excercise โ€“ 18

scmuser created the topic: how to restore the dump file using shell scripting I have created a script file to dump the application files using the following…

Read More

Shell Bash Scripting: Assignment & Excercise โ€“ 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell Bash Scripting: Assignment & Excercise โ€“ 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Chef Tutorials: Chef Infra Server & Chef Automate Backup and Restore

Chef Infra Server is backed up with chef-server-ctl backup and restored with chef-server-ctl restore. Chef Automate has its own commands, chef-automate backup create and chef-automate backup restore….

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Suraj Rampure
Suraj Rampure
3 years ago

Sir,
This is great information

1
0
Would love your thoughts, please comment.x
()
x