KatInterview

Safely Count Regular Files in Directory Trees via Bash

System DesignModel answer
MediumModel answerSystem Designbashlinuxshell-scripting

Last updated

Write a robust Bash function that counts regular files across a directory tree, handling embedded newlines, spaces, leading hyphens, and traversal constraints safely.

Task

Write a robust, POSIX-compliant Bash function named count_files that returns the total count of regular files located within a specified target directory (including all subdirectories).

Requirements

  1. Invocation Interface:

    count_files [-L] [--max-depth N] <target_directory>
    
    • <target_directory>: Path to the directory to inspect.
    • -L (optional flag): Follow symbolic links to directories during traversal.
    • --max-depth N (optional flag): Restrict traversal depth to at most N directory levels (where 0 evaluates only the root target itself, 1 includes immediate children, etc.). If omitted, recurse without depth restriction.
  2. Filtering Rules: Count only regular files. Exclude directories, broken symlinks, symlinks to directories (unless -L is passed and resolves them to a regular file), sockets, FIFOs, and special character/block devices.

  3. Output & Status Code:

    • Print the exact integer count to stdout, terminated by a newline.
    • Return exit code 0 on success.
    • Print an error message to stderr and return a non-zero exit code if the directory does not exist, cannot be read, or if invalid options are provided.

Robustness & Constraints

Your implementation must handle complex edge cases without miscounting or executing unintended shell commands:

  • Filenames containing spaces, tabs, and embedded newline (\n) characters.
  • Hidden files and hidden directories (dotfiles like .env or .git/).
  • Target paths or filenames starting with leading dashes (e.g., -rf, --help).
  • Performance: Trees may contain hundreds of thousands of files; avoid holding all paths in a shell memory array or spawning one shell process per file.

Example

Given a directory sample_dir/ containing:

  • data.json (regular file)
  • .secrets (hidden regular file)
  • "report\nwith\nnewlines.txt" (regular file containing embedded newlines)
  • nested/ (directory containing item.bin)
  • dangling_symlink (symlink pointing to a missing path)
$ count_files sample_dir
4

$ count_files --max-depth 1 sample_dir
3

Hints

Hint 1

Avoid parsing filenames line-by-line using `wc -l` or string splitting, because newline characters within filenames distort line counts.

Hint 2

Instead of printing path strings, configure `find` to output a fixed-size token (or character byte) for each matched regular file and count the stream length.

Hint 3

To prevent target paths with leading dashes from being interpreted as `find` flags, prefix relative target paths with `./` before passing them to the command.