How to compare the current date with past 60 days using shell script

Learn how to compare the current date with past 60 days using shell script with practical examples, diagrams, and best practices. Covers shell development techniques with visual explanations.

Comparing Current Date with Past 60 Days in Shell Scripts

Hero image for How to compare the current date with past 60 days using shell script

Learn how to effectively compare the current date against a 60-day historical window using various shell scripting techniques, ensuring your scripts can make time-sensitive decisions.

Shell scripting often requires comparing dates to determine if a file is old, a log entry is recent, or a task needs to be executed based on a time window. A common requirement is to check if a given date falls within the last 60 days from the current date. This article will guide you through different methods to achieve this comparison using standard shell utilities like date and awk.

Understanding Date Formats and Epoch Time

Before diving into comparisons, it's crucial to understand how dates are represented and manipulated in shell scripts. The most reliable way to compare dates numerically is by converting them into 'Epoch time' (also known as Unix time). Epoch time is the number of seconds that have elapsed since January 1, 1970 (UTC). This conversion simplifies comparisons as it reduces dates to a single, comparable integer.

flowchart TD
    A[Start] --> B{Get Current Date}
    B --> C[Convert Current Date to Epoch]
    C --> D{Get Target Date (e.g., file modification date)}
    D --> E[Convert Target Date to Epoch]
    E --> F{Calculate 60 Days in Seconds}
    F --> G{Compare: Current Epoch - Target Epoch <= 60 Days Seconds?}
    G -- Yes --> H[Date is within 60 days]
    G -- No --> I[Date is older than 60 days]
    H --> J[End]
    I --> J

Workflow for comparing dates using Epoch time.

Method 1: Using date Command for Epoch Comparison

The date command is a powerful utility available in most Unix-like systems. It can convert dates to and from Epoch time, making it ideal for our comparison. We'll calculate the Epoch time for the current date and the date 60 days ago, then compare our target date against this range.

#!/bin/bash

# Get current date in Epoch seconds
CURRENT_EPOCH=$(date +%s)

# Calculate Epoch seconds for 60 days ago
# macOS/BSD date command uses -v for relative dates
# Linux date command uses -d for relative dates

# For Linux (GNU date):
# SIXTY_DAYS_AGO_EPOCH=$(date -d "60 days ago" +%s)

# For macOS/BSD (requires gdate if you want -d, otherwise use -v):
# SIXTY_DAYS_AGO_EPOCH=$(date -v-60d +%s)

# Generic approach using arithmetic (less precise for leap seconds/DST, but often sufficient)
# Or, if you have GNU date, prefer the -d option.
# Let's assume GNU date for simplicity here, as it's common in servers.
SIXTY_DAYS_AGO_EPOCH=$(date -d "60 days ago" +%s)

# Example target date (e.g., a file's last modification time)
# For demonstration, let's pick a date. Replace with actual file date.
TARGET_DATE_STR="2023-10-20 10:00:00"
TARGET_EPOCH=$(date -d "$TARGET_DATE_STR" +%s)

echo "Current Epoch: $CURRENT_EPOCH"
echo "60 Days Ago Epoch: $SIXTY_DAYS_AGO_EPOCH"
echo "Target Epoch ($TARGET_DATE_STR): $TARGET_EPOCH"

if (( TARGET_EPOCH >= SIXTY_DAYS_AGO_EPOCH && TARGET_EPOCH <= CURRENT_EPOCH )); then
    echo "The target date is within the last 60 days."
else
    echo "The target date is NOT within the last 60 days."
fi

# Example with a file's modification time
# touch -d "2 months ago" old_file.txt
# touch -d "1 month ago" recent_file.txt

# FILE_PATH="recent_file.txt" # or "old_file.txt"
# if [ -f "$FILE_PATH" ]; then
#     FILE_MOD_EPOCH=$(stat -c %Y "$FILE_PATH") # Linux
#     # FILE_MOD_EPOCH=$(stat -f %m "$FILE_PATH") # macOS/BSD
#     echo "\nFile '$FILE_PATH' modification Epoch: $FILE_MOD_EPOCH"
#     if (( FILE_MOD_EPOCH >= SIXTY_DAYS_AGO_EPOCH && FILE_MOD_EPOCH <= CURRENT_EPOCH )); then
#         echo "File '$FILE_PATH' was modified within the last 60 days."
#     else
#         echo "File '$FILE_PATH' was modified more than 60 days ago."
#     fi
# else
#     echo "File '$FILE_PATH' not found."
# fi

Shell script using date to compare a target date with the last 60 days.

Method 2: Using awk for Date Calculations (More Complex but Portable)

While date is convenient, awk can also perform date calculations, especially if you need to process dates from a file line by line without spawning many date sub-processes. awk's mktime function converts a date string into Epoch time, similar to date +%s.

#!/bin/bash

# Get current date in Epoch seconds
CURRENT_EPOCH=$(date +%s)

# Calculate 60 days in seconds (60 days * 24 hours * 60 minutes * 60 seconds)
SIXTY_DAYS_IN_SECONDS=$((60 * 24 * 60 * 60))

# Calculate the Epoch time for 60 days ago
SIXTY_DAYS_AGO_EPOCH=$((CURRENT_EPOCH - SIXTY_DAYS_IN_SECONDS))

# Example target dates (replace with actual data source)
TARGET_DATES=(
    "2023 11 15 10 30 00" # Within 60 days
    "2023 08 01 12 00 00" # Older than 60 days
    "2023 12 20 05 00 00" # Future date (also within range if current is 2024-01-10)
)

echo "Current Epoch: $CURRENT_EPOCH"
echo "60 Days Ago Epoch: $SIXTY_DAYS_AGO_EPOCH"

for date_str in "${TARGET_DATES[@]}"; do
    # Convert target date string to Epoch using awk's mktime
    # mktime expects "YYYY MM DD HH MM SS"
    TARGET_EPOCH=$(echo "$date_str" | awk '{ print mktime($0) }')

    echo "\nTarget Date String: $date_str"
    echo "Target Epoch: $TARGET_EPOCH"

    if (( TARGET_EPOCH >= SIXTY_DAYS_AGO_EPOCH && TARGET_EPOCH <= CURRENT_EPOCH )); then
        echo "  -> The target date is within the last 60 days."
    else
        echo "  -> The target date is NOT within the last 60 days."
    fi
done

Shell script using awk's mktime for date comparison.

Practical Application: Cleaning Old Files

A common use case for date comparison is to identify and clean up files older than a certain period. While find has its own -mtime (modification time) option, understanding the Epoch comparison allows for more complex logic or when find's options aren't sufficient.

#!/bin/bash

# Define the directory to clean
TARGET_DIR="/path/to/your/logs" # IMPORTANT: Change this to your actual directory

# Number of days to keep
DAYS_TO_KEEP=60

# Calculate the Epoch time for the cutoff date
# Using GNU date for simplicity
CUTOFF_EPOCH=$(date -d "$DAYS_TO_KEEP days ago" +%s)

echo "Cleaning files in: $TARGET_DIR"
echo "Keeping files modified within the last $DAYS_TO_KEEP days (Cutoff Epoch: $CUTOFF_EPOCH)"

# Check if the directory exists
if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' not found." >&2
    exit 1
fi

# Iterate through files in the target directory
# Using find to get file paths, then stat to get modification time
find "$TARGET_DIR" -type f -print0 | while IFS= read -r -d $'
' file;
do
    # Get file modification time in Epoch seconds
    FILE_MOD_EPOCH=$(stat -c %Y "$file") # Linux (GNU stat)
    # FILE_MOD_EPOCH=$(stat -f %m "$file") # macOS/BSD

    if (( FILE_MOD_EPOCH < CUTOFF_EPOCH )); then
        echo "Deleting old file: $file (Modified Epoch: $FILE_MOD_EPOCH)"
        # Uncomment the line below to actually delete files
        # rm "$file"
    else
        echo "Keeping recent file: $file (Modified Epoch: $FILE_MOD_EPOCH)"
    fi
done

echo "Cleanup process complete."

Script to identify and optionally delete files older than 60 days.