Shell Scripting: Finding the Largest File in a Directory

Shell Scripting @ Freshers.in

Shell scripting is a powerful tool for automating tasks and performing operations on files and directories. In this article, we’ll explore how to write a shell script that takes a directory name as an argument and finds the largest file within it. We’ll delve into the script’s implementation, provide examples, and showcase the output to demonstrate its functionality.

Understanding the Shell Script:

The shell script we’ll be creating will use basic Unix commands and shell scripting constructs to traverse the specified directory, identify files, and determine the largest file based on its size.

Script Implementation:

#!/bin/bash

# Check if directory name argument is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

# Assign directory name to a variable
directory="$1"

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

# Find the largest file in the directory
largest_file=""
max_size=0

for file in "$directory"/*; do
    if [ -f "$file" ]; then
        size=$(stat -c %s "$file")
        if [ "$size" -gt "$max_size" ]; then
            max_size="$size"
            largest_file="$file"
        fi
    fi
done

# Display the largest file
if [ -n "$largest_file" ]; then
    echo "The largest file in '$directory' is: $largest_file"
    echo "Size: $(du -h "$largest_file" | cut -f1)"
else
    echo "No files found in '$directory'."
fi

Example Usage:

Suppose we have a directory named “documents” containing various files. We’ll execute the shell script with the directory name as an argument to find the largest file within it.

$ ./find_largest_file.sh documents

Output:

The output of the script will display the path of the largest file found within the specified directory, along with its size.

The largest file in 'documents' is: /path/to/documents/large_file.txt
Size: 5.2M

Other urls to refer

  1. PySpark Blogs
Author: user