Argument Handling in Shell Scripting: Counting Lines in a File

Shell Scripting @ Freshers.in

One common task is processing files based on user input. In this comprehensive guide, we’ll explore how to write a shell script that accepts a filename as an argument and prints the number of lines in that file.

Understanding Shell Scripting

Shell scripting is a powerful tool for automating tasks and executing commands in Unix-like operating systems. Whether you’re a system administrator, developer, or power user, understanding shell scripting opens up a world of possibilities for automating repetitive tasks and streamlining workflows.

The Importance of Argument Handling

Shell scripts often need to process user-provided arguments to perform specific tasks. Properly handling these arguments ensures that scripts are flexible, user-friendly, and robust. Whether it’s parsing command-line options or processing file names, effective argument handling is a fundamental skill for any shell script developer.

The Challenge: Counting Lines in a File

Our goal is to create a shell script that accepts a filename as an argument and prints the number of lines in that file. While this might seem like a simple task, it involves understanding how to handle arguments passed to a script and efficiently process the specified file to count its lines.

Writing the Shell Script

Let’s dive into the process of creating a robust shell script that counts the lines in a specified file. We’ll break down the script into manageable steps, ensuring clarity and understanding at each stage.

Step 1: Accepting Filename as an Argument

Our script needs to accept a filename as an argument provided by the user. We’ll use the $1 variable to access the first argument passed to the script.

#!/bin/bash
# Check if filename is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi
filename="$1"

Step 2: Counting Lines in the File

Now that we have the filename, we’ll use the wc command to count the number of lines in the specified file. We’ll then extract and print the line count using command substitution.

#!/bin/bash
# Check if filename is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi
filename="$1"
# Count lines in the file
line_count=$(wc -l < "$filename")
echo "Number of lines in $filename: $line_count"

Testing and Validation

Testing is essential to ensure that our script behaves as expected in different scenarios. We’ll test our script with various filenames, including files with different line counts, non-existent files, and empty files, to validate its correctness and robustness

Author: user