← Back to all snippets
BASH

Find Files Modified Recently

Quickly locate files modified within a specific number of days using this Bash script, ideal for monitoring recent changes in a project directory.

#!/bin/bash

# Default directory and days
TARGET_DIR="."
DAYS=7

# Parse arguments for directory and days
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        -d|--dir) TARGET_DIR="$2"; shift ;;
        -n|--days) DAYS="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

echo "Searching for files modified in the last $DAYS days in directory: $TARGET_DIR"

# Find files modified in the last N days
# -type f: only regular files
# -mtime -N: files modified less than N*24 hours ago
find "$TARGET_DIR" -type f -mtime "-$DAYS" -print0 | xargs -0 ls -lht

# Example usage:
# ./find_recent.sh -d /var/www/my_project -n 3
# ./find_recent.sh --days 14
How it works: This script uses the `find` command to locate files modified within a specified number of days in a given directory. It takes optional arguments for the target directory (`-d` or `--dir`) and the number of days (`-n` or `--days`). The `find` command with `-mtime -N` option is central to this, finding files modified less than N*24 hours ago, and `xargs` is used to list the found files with detailed information. This helps web developers quickly identify recently changed project assets, configuration files, or log files.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs