Creating Backup Folder
Part of the Fundamentals section of Coddy's Terminal journey — lesson 76 of 82.
Challenge
EasyNow 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.shEach 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.shFinally, 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.shYour output should be:
Backing up: documents
Created backup folder: backupVerify 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
-pflag inmkdir -pprevents 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
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.shAll lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder11Permissions
Understanding PermissionsReading PermissionsChmod With NumbersChmod With SymbolsFile OwnershipRecap - Lock It Down14Backup Script Project
Project OverviewGetting The Source Path6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline