>_ IzzyLab

Hands-on task

This task is step 7 of the course “Your first bash script”

A for loop: a copy of every log

easy~7 min

The directory /root/logs holds logs — *.log files — and some other files next to them. Write the script /root/backup-logs.sh that uses a for loop to go through all the *.log files in that directory and, next to each one, makes a copy with a .bak suffix added: app.log → app.log.bak. Leave the other files alone.

There will be more logs over time, so don't write the file names into the script — let it find them on its own. When the script is ready, run it.

What you'll practise:
  • bash scripts
  • for loop
  • filename patterns
  • cp

Topic breakdown

A for loop repeats commands for every item in a list:

for name in item1 item2 item3; do
    commands where $name is the current item
done

For example:

for host in web-01 web-02 db-01; do
    echo "checking $host"
done

You don't have to type the list by hand. bash replaces a pattern with an asterisk with the names of the matching files: /etc/*.conf becomes /etc/adduser.conf /etc/host.conf …. So a loop over files looks like this:

for f in /etc/*.conf; do
    echo "config: $f"
done

$f holds the full path to each file in turn. When a new .conf appears, the loop picks it up without changing the script.

Put a variable with a file name in double quotes ("$f"): that way a name with a space doesn't fall apart into two words.

What's checked

  1. /root/backup-logs.sh created
  2. Every log has a .bak copy
  3. There are no other copies
  4. The script finds new logs too

What it looks like