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.
Rewrite backup.sh so it holds the complete, updated script (run cat backup.sh to see the previous lesson's version):
- Keep every other line of the previous lesson's script as it is
- 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"Writing a multi-line script with one
echoper line works, but there is a shorter way: a here document feeds everything up to the closing word straight into the file.cat > script.sh << 'EOF' #!/bin/bash echo "hello" EOFThe quotes around
'EOF'keep$variablesfrom being expanded while the file is written, which is what you want when the script itself uses them.
Run the script with documents as the input (echo "documents" | bash backup.sh). 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
echo 'cp "$source_dir"/* "$backup_dir"' >> backup.sh
echo 'echo "Files copied successfully"' >> backup.sh
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 PipelinePractice on your own: Terminal playground