How to Append Current Timestamp and File Count to a Log File in Linux Shell Script


2 views

Many Linux administrators need to regularly log both system metrics and timestamps for monitoring purposes. A common requirement is logging the current date/time along with the count of files in a specific directory.

The simplest way to achieve this combines date and file counting commands:

echo "$(date) - $(ls | wc -l) files" >> /root/log.txt

For better readability and parsing, consider using ISO 8601 format:

echo "$(date --iso-8601=seconds) - $(ls -1 | wc -l) files" >> /root/log.txt

For a cron job that runs every hour:

0 * * * * /usr/bin/echo "$(date --iso-8601=seconds) - $(ls -1 /path/to/dir | wc -l) files" >> /var/log/filecount.log

A more robust shell script version:

#!/bin/bash
LOG_FILE="/var/log/filecount.log"
TARGET_DIR="/path/to/dir"

if [ -d "$TARGET_DIR" ]; then
    TIMESTAMP=$(date --iso-8601=seconds)
    FILE_COUNT=$(ls -1 "$TARGET_DIR" 2>/dev/null | wc -l)
    echo "${TIMESTAMP} - ${FILE_COUNT} files" >> "$LOG_FILE"
else
    echo "$(date --iso-8601=seconds) - ERROR: Directory $TARGET_DIR not found" >> "$LOG_FILE"
fi

For more accurate file counting (excluding directories and hidden files):

echo "$(date) - $(find /path/to/dir -maxdepth 1 -type f | wc -l) regular files" >> log.txt

When setting up cron jobs for directory monitoring, it's common to need both the file count and timestamp information. Here's how to properly format this:

echo "$(date '+%Y-%m-%d %H:%M:%S') - $(ls | wc -l) files" >> /root/log.txt

The command consists of three key components:

  • date '+%Y-%m-%d %H:%M:%S' - Formats the current timestamp
  • ls | wc -l - Counts files in the current directory
  • >> - Appends to the log file without overwriting

For better reliability and explicit directory targeting:

echo "$(date '+%Y-%m-%d %H:%M:%S') - $(ls /path/to/directory | wc -l) files in /path/to/directory" >> /var/log/directory_monitor.log

To run this every hour via cron:

0 * * * * echo "$(date '+\%Y-\%m-\%d \%H:\%M:\%S') - $(ls /target/dir | wc -l) files" >> /var/log/monitor.log

Note the escaped percent signs in cron.

If you need to count hidden files (dotfiles) as well:

echo "$(date '+%Y-%m-%d %H:%M:%S') - $(find /path/to/dir -maxdepth 1 -type f | wc -l) files" >> log.txt

A more robust script version with error checking:

#!/bin/bash
LOG_FILE="/var/log/dir_monitor.log"
TARGET_DIR="/path/to/directory"

if [ -d "$TARGET_DIR" ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $(ls "$TARGET_DIR" | wc -l) files in $TARGET_DIR" >> "$LOG_FILE"
else
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: Directory $TARGET_DIR not found" >> "$LOG_FILE"
fi

The log entries will appear like this:

2023-11-15 14:00:01 - 42 files in /path/to/directory
2023-11-15 15:00:01 - 45 files in /path/to/directory