🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Capstone: A Backup Script

A backup script copies important files to a safe place. This capstone builds one from the pieces of this course: variables, a function, and a loop.

Name the backup with a label

The label names the backup folder. mkdir -p makes the folder.

label="daily"
mkdir -p "backup-$label"
ls -d backup-daily

Copy each file in a loop

The for loop takes one file at a time. cp copies it into the backup folder.

mkdir -p backup-daily
for file in notes.txt shopping.txt; do
  cp "$file" backup-daily/
done
ls backup-daily

Count the files

ls lists the backup folder, and wc -l counts the lines. The count is 4.

mkdir -p backup-daily
cp notes.txt shopping.txt data.csv report.txt backup-daily/
count=$(ls backup-daily | wc -l)
echo "Backed up $((count)) files to backup-daily."

Hold the copy step in a function

backup_file copies one file. The loop calls it for each file.

backup_file() {
  cp "$1" backup-one/
}
mkdir -p backup-one
backup_file notes.txt
ls backup-one

Example

cat > backup.sh << 'EOF'
#!/bin/bash
label=$1
mkdir -p "backup-$label"
backup_file() {
  cp "$1" "backup-$label/"
}
for file in notes.txt shopping.txt data.csv report.txt; do
  backup_file "$file"
done
count=$(ls "backup-$label" | wc -l)
echo "Backed up $((count)) files to backup-$label."
echo "Backup done."
EOF
bash backup.sh daily

Key points

  • Backup: a copy of files kept safe in case the first copy is lost.
  • Use a variable to hold the label for a backup folder.
  • Use a function to hold the copy step in one place.
  • Use a for loop to copy each file in turn.
  • Use ls | wc -l to count the files in the backup folder.

In this example, backup.sh takes daily as its label and makes backup-daily. The function copies each file. The loop runs it four times. Then the script prints the count and a done line.

Note

Run the script with a label, as in ./backup.sh daily.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In the backup script, what does $1 hold?