Shell Scripting: Displaying Last 10 Lines of a File

Shell Scripting @ Freshers.in

Introduction to Shell Scripting for File Manipulation

Shell scripting is a versatile tool for automating tasks in Unix-like operating systems. In this article, we’ll explore how to write a Shell script that takes a file name as an argument and displays the last 10 lines of it. We’ll provide a step-by-step explanation of the script, along with practical examples and output.

Understanding File Manipulation in Shell Scripting

File manipulation is a common task in Shell scripting, allowing users to perform various operations on files and directories. Displaying the last few lines of a file is a useful operation for viewing log files, monitoring system activity, and debugging scripts.

Writing the Last 10 Lines Display Script

Let’s create a Shell script named display_last_lines.sh that takes a file name as an argument and displays the last 10 lines of the file.

#!/bin/bash
# Check if the correct number of arguments are provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <file_name>"
    exit 1
fi
# Assign argument to variable
file_name=$1
# Display last 10 lines of the file
tail -n 10 "$file_name"

We use the tail command to display the last 10 lines of a file.

The -n flag specifies the number of lines to display, in this case, 10.

The script takes one argument: the file name provided by the user.

The "$file_name" variable holds the name of the file provided as an argument.

Example Usage and Output

Let’s assume we have a file named example.txt containing some text.

$ ./display_last_lines.sh example.txt

Output:

line 1
line 2
line 3
...
line 8
line 9
line 10
Author: user