Menu
CoddyTech

Adding A Timestamp

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

challenge icon

Challenge

Easy

Let'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):

  1. Keep every other line of the previous lesson's script as it is
  2. Replace the static backup_dir="backup" with a dynamic name that includes a timestamp
  3. Use command substitution with the date command to generate a timestamp in the format YYYYMMDD_HHMMSS
  4. The backup folder should be named: backup_[timestamp]

The date command with format specifiers creates timestamps:

date +%Y%m%d_%H%M%S

Use 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 echo per 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"
EOF

The quotes around 'EOF' keep $variables from 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 successfully

The 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 defining backup_dir, then use backup_dir="backup_$timestamp" to create the dynamic folder name.

Try it yourself

Terminal
echo 'cp "$source_dir"/* "$backup_dir"' >> backup.sh
echo 'echo "Files copied successfully"' >> backup.sh
echo "documents" | bash backup.sh
ls backup

All lessons in Fundamentals

Practice on your own: Terminal playground