Adding A Timestamp
Part of the Fundamentals section of Coddy's Terminal journey — lesson 78 of 82.
Challenge
EasyLet's make the backup folder name unique by adding a timestamp. This way, each backup creates a new folder instead of overwriting the previous one.
Modify backup.sh to:
- Keep all the existing code from the previous lesson
- Replace the static
backup_dir="backup"with a dynamic name that includes a timestamp - Use command substitution with the
datecommand to generate a timestamp in the formatYYYYMMDD_HHMMSS - The backup folder should be named:
backup_[timestamp]
The date command with format specifiers creates timestamps:
date +%Y%m%d_%H%M%SUse command substitution $(command) to capture this output in a variable:
timestamp=$(date +%Y%m%d_%H%M%S)
backup_dir="backup_$timestamp"Run the script and enter documents when prompted. Your output should look like:
Backing up: documents
Created backup folder: backup_20240115_143052
Files copied successfullyThe timestamp in your output will be different based on the current date and time.
Hint: Add
timestamp=$(date +%Y%m%d_%H%M%S)before definingbackup_dir, then usebackup_dir="backup_$timestamp"to create the dynamic folder name.
Try it yourself
cat > backup.sh << 'EOF'
#!/bin/bash
read -p "Enter source directory: " source_dir
echo "Backing up: $source_dir"
backup_dir="backup"
mkdir -p "$backup_dir"
echo "Created backup folder: $backup_dir"
cp "$source_dir"/* "$backup_dir"
echo "Files copied successfully"
EOF
echo "documents" | bash backup.sh
ls backupAll 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