Menu
Coddy logo textTech

Creating Backup Folder

Part of the Fundamentals section of Coddy's Terminal journey. Lesson 76 of 82.

challenge icon

Challenge

Easy

Now let's extend the backup script to create a backup folder where the files will be stored.

Rewrite backup.sh from scratch so it holds the complete, updated script. Use > for the first line to replace the file, then >> to append each following line:

echo '#!/bin/bash' > backup.sh
echo 'read -p "Enter source directory: " source_dir' >> backup.sh
echo 'echo "Backing up: $source_dir"' >> backup.sh
echo 'backup_dir="backup"' >> backup.sh
echo 'mkdir -p "$backup_dir"' >> backup.sh
echo 'echo "Created backup folder: $backup_dir"' >> backup.sh

Each line is wrapped in single quotes so the shell writes $source_dir and $backup_dir into the file literally instead of replacing them with their values.

Then make it executable:

chmod +x backup.sh

Finally, run your script with documents as the input. This terminal is not interactive, so pipe the answer into the script instead of waiting to be asked:

echo "documents" | ./backup.sh

Your output should be:

Backing up: documents
Created backup folder: backup

Verify the folder was created by running ls to list the directory contents. The output should show the new backup folder alongside your other files.

Hint: The -p flag in mkdir -p prevents errors if the directory already exists. Make sure to use quotes around your variables (e.g., "$backup_dir") to handle them safely.

Try it yourself

Terminal
echo '#!/bin/bash' > backup.sh
echo 'read -p "Enter source directory: " source_dir' >> backup.sh
echo 'echo "Backing up: $source_dir"' >> backup.sh
chmod +x backup.sh
echo "documents" | ./backup.sh

All lessons in Fundamentals

Practice on your own: Terminal playground