Menu
Coddy logo textTech

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.

Modify backup.sh to:

  1. Keep all the existing code from the previous lesson
  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"

Run the script and enter documents when prompted. 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
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 backup

All lessons in Fundamentals