Katkat

Find largest file in a directory using Bash

IntuitSoftware Engineer · Online Assessment

Last updated

This problem tests your ability to navigate the file system using command-line utilities and process streaming data to identify files based on size metadata.

Problem Statement

Given a root directory path, write a shell script (compatible with Bash) that finds and prints the absolute path and size (in bytes) of the single largest regular file located within that directory or any of its subdirectories.

Requirements

  1. You must traverse the directory recursively.
  2. You must ignore directories, symbolic links, sockets, and other special file types; only consider regular files.
  3. The script should be robust enough to handle filenames containing spaces, tabs, or newlines.
  4. If multiple files share the same maximum size, printing any one of them is acceptable.
  5. If the provided directory is empty or contains no regular files, the script should exit gracefully without error output.

Expected Output

The output should be formatted as follows: .

Example

Input: /home/user/documents

Output: 1048576 /home/user/documents/archive/backup.tar

Constraints

  • The script should run on a standard Linux environment.
  • Avoid hard-coding absolute paths inside the script except for the root directory provided as an argument.
  • Consider efficiency; the script should perform reasonably well on directories with thousands of files.

Hints

Hint 1

Consider using the 'find' command with appropriate flags to filter for regular files.

Hint 2

The 'stat' or 'du' commands can be used to extract file size information, but ensure you handle special characters correctly using null delimiters.

Hint 3

Look into sorting streams of data using 'sort -n' to identify the largest entry.

Follow-up questions

  • How would you modify your script to find the top 5 largest files instead of just the single largest?
  • What changes would be necessary to exclude specific file extensions (e.g., '.tmp' or '.log') from the search?
  • If the directory contains millions of files, how would the performance of your script change, and how could you optimize it?