DEV Community

Fahad Vahora
Fahad Vahora

Posted on

Linux Practical Set E Solution – Display Lines from a File with Validation

In this article, we will solve VNSGU TYBCA Semester 5 Linux (UNIX) Practical – Set E using shell scripting.

This practical focuses on:

  • Command-line arguments
  • File validation
  • Numeric validation
  • Line range validation
  • Displaying specific lines from a file
  • sed
  • head
  • tail

📌 Practical Question

Write a shell script that will pass file name and two numbers a1 and a2. Display line a1 to a2 from that file. [Proper validation required]

The script should accept:

filename
a1 = starting line number
a2 = ending line number
Enter fullscreen mode Exit fullscreen mode

For example:

./script.sh marks.txt 3 7
Enter fullscreen mode Exit fullscreen mode

This should display lines 3 to 7 from marks.txt.


🧠 What Are Command-Line Arguments?

When a shell script is executed, values can be passed directly from the command line.

Example:

./script.sh marks.txt 3 7
Enter fullscreen mode Exit fullscreen mode

Here:

Argument Meaning
$0 Script name
$1 File name
$2 Starting line
$3 Ending line
$# Number of arguments

So:

$1 = marks.txt
$2 = 3
$3 = 7
Enter fullscreen mode Exit fullscreen mode

✅ Solution 1: Using sed with Proper Validation

sed is a very suitable command for displaying a specific range of lines.

Shell Script

#!/bin/bash

# Check number of arguments
if [ $# -ne 3 ]
then
    echo "Usage: $0 <file> <start_line> <end_line>"
    exit 1
fi

file=$1
a1=$2
a2=$3

# Check whether file exists
if [ ! -f "$file" ]
then
    echo "Error: File does not exist."
    exit 1
fi

# Check whether file is readable
if [ ! -r "$file" ]
then
    echo "Error: File is not readable."
    exit 1
fi

# Check whether a1 is a positive integer
if ! [[ "$a1" =~ ^[1-9][0-9]*$ ]]
then
    echo "Error: Starting line must be a positive integer."
    exit 1
fi

# Check whether a2 is a positive integer
if ! [[ "$a2" =~ ^[1-9][0-9]*$ ]]
then
    echo "Error: Ending line must be a positive integer."
    exit 1
fi

# Check line range
if [ "$a1" -gt "$a2" ]
then
    echo "Error: Starting line must be less than or equal to ending line."
    exit 1
fi

# Check whether starting line exists
total_lines=$(wc -l < "$file")

if [ "$a1" -gt "$total_lines" ]
then
    echo "Error: Starting line is beyond the end of the file."
    exit 1
fi

echo "Displaying lines $a1 to $a2 from $file:"
sed -n "${a1},${a2}p" "$file"
Enter fullscreen mode Exit fullscreen mode

🔍 Step-by-Step Explanation

Step 1: Validate Number of Arguments

if [ $# -ne 3 ]
Enter fullscreen mode Exit fullscreen mode

The script requires exactly 3 arguments:

1. File name
2. Starting line
3. Ending line
Enter fullscreen mode Exit fullscreen mode

For example:

./script.sh marks.txt 3 7
Enter fullscreen mode Exit fullscreen mode

If the user enters:

./script.sh marks.txt 3
Enter fullscreen mode Exit fullscreen mode

the script displays the correct usage and exits.


Step 2: Store Arguments in Variables

file=$1
a1=$2
a2=$3
Enter fullscreen mode Exit fullscreen mode

Now the values are easier to understand.

file → marks.txt
a1   → 3
a2   → 7
Enter fullscreen mode Exit fullscreen mode

Step 3: Check File Existence

if [ ! -f "$file" ]
Enter fullscreen mode Exit fullscreen mode

The -f test checks whether the given path is a regular file.

If the file does not exist:

Error: File does not exist.
Enter fullscreen mode Exit fullscreen mode

and the script stops.


Step 4: Check File Read Permission

if [ ! -r "$file" ]
Enter fullscreen mode Exit fullscreen mode

The -r test checks whether the file is readable.

This prevents the script from trying to read a file that the current user cannot access.


Step 5: Validate Starting Line

if ! [[ "$a1" =~ ^[1-9][0-9]*$ ]]
Enter fullscreen mode Exit fullscreen mode

This checks that a1 contains a positive integer.

Valid examples:

1
5
10
100
Enter fullscreen mode Exit fullscreen mode

Invalid examples:

0
-5
abc
2.5
Enter fullscreen mode Exit fullscreen mode

Step 6: Validate Ending Line

The same validation is applied to a2:

if ! [[ "$a2" =~ ^[1-9][0-9]*$ ]]
Enter fullscreen mode Exit fullscreen mode

This ensures that the ending line is also a positive integer.


Step 7: Validate the Range

if [ "$a1" -gt "$a2" ]
Enter fullscreen mode Exit fullscreen mode

The starting line cannot be greater than the ending line.

For example:

a1 = 3
a2 = 7
Enter fullscreen mode Exit fullscreen mode

is valid.

But:

a1 = 7
a2 = 3
Enter fullscreen mode Exit fullscreen mode

is invalid.


Step 8: Find Total Number of Lines

total_lines=$(wc -l < "$file")
Enter fullscreen mode Exit fullscreen mode

This stores the total number of lines in the file.

For example, if the file contains 20 lines:

total_lines = 20
Enter fullscreen mode Exit fullscreen mode

Step 9: Check Starting Line

if [ "$a1" -gt "$total_lines" ]
Enter fullscreen mode Exit fullscreen mode

If the requested starting line is beyond the end of the file, the script displays an error.

For example:

File has 10 lines
a1 = 15
Enter fullscreen mode Exit fullscreen mode

There is no line 15, so the request is invalid.


Step 10: Display the Required Lines

sed -n "${a1},${a2}p" "$file"
Enter fullscreen mode Exit fullscreen mode

Suppose:

a1 = 3
a2 = 7
Enter fullscreen mode Exit fullscreen mode

Then:

sed -n '3,7p' marks.txt
Enter fullscreen mode Exit fullscreen mode

prints lines:

3
4
5
6
7
Enter fullscreen mode Exit fullscreen mode

🖥️ Example File

Suppose marks.txt contains:

Line 1 - Linux
Line 2 - UNIX
Line 3 - Shell
Line 4 - Bash
Line 5 - Commands
Line 6 - File Handling
Line 7 - Text Processing
Line 8 - Permissions
Line 9 - Processes
Line 10 - Networking
Enter fullscreen mode Exit fullscreen mode

Run:

./script.sh marks.txt 3 7
Enter fullscreen mode Exit fullscreen mode

Output:

Displaying lines 3 to 7 from marks.txt:
Line 3 - Shell
Line 4 - Bash
Line 5 - Commands
Line 6 - File Handling
Line 7 - Text Processing
Enter fullscreen mode Exit fullscreen mode

❌ Validation Examples

Missing Arguments

./script.sh marks.txt 3
Enter fullscreen mode Exit fullscreen mode

Output:

Usage: ./script.sh <file> <start_line> <end_line>
Enter fullscreen mode Exit fullscreen mode

File Does Not Exist

./script.sh abc.txt 2 5
Enter fullscreen mode Exit fullscreen mode

Output:

Error: File does not exist.
Enter fullscreen mode Exit fullscreen mode

Invalid Starting Line

./script.sh marks.txt abc 5
Enter fullscreen mode Exit fullscreen mode

Output:

Error: Starting line must be a positive integer.
Enter fullscreen mode Exit fullscreen mode

Invalid Ending Line

./script.sh marks.txt 2 xyz
Enter fullscreen mode Exit fullscreen mode

Output:

Error: Ending line must be a positive integer.
Enter fullscreen mode Exit fullscreen mode

Invalid Range

./script.sh marks.txt 8 3
Enter fullscreen mode Exit fullscreen mode

Output:

Error: Starting line must be less than or equal to ending line.
Enter fullscreen mode Exit fullscreen mode

Starting Line Beyond File

If the file contains only 10 lines:

./script.sh marks.txt 15 20
Enter fullscreen mode Exit fullscreen mode

Output:

Error: Starting line is beyond the end of the file.
Enter fullscreen mode Exit fullscreen mode

🔄 Solution 2: Using awk

The same task can also be performed using awk.

Shell Script

#!/bin/bash

if [ $# -ne 3 ]
then
    echo "Usage: $0 <file> <start_line> <end_line>"
    exit 1
fi

file=$1
a1=$2
a2=$3

if [ ! -f "$file" ]
then
    echo "Error: File does not exist."
    exit 1
fi

if [ ! -r "$file" ]
then
    echo "Error: File is not readable."
    exit 1
fi

if ! [[ "$a1" =~ ^[1-9][0-9]*$ ]] || ! [[ "$a2" =~ ^[1-9][0-9]*$ ]]
then
    echo "Error: Line numbers must be positive integers."
    exit 1
fi

if [ "$a1" -gt "$a2" ]
then
    echo "Error: Invalid line range."
    exit 1
fi

awk -v start="$a1" -v end="$a2" \
    'NR >= start && NR <= end {print}' "$file"
Enter fullscreen mode Exit fullscreen mode

How awk Works

NR represents the current record/line number.

This condition:

NR >= start && NR <= end
Enter fullscreen mode Exit fullscreen mode

means:

Print lines whose line number is between start and end.

For:

start = 3
end = 7
Enter fullscreen mode Exit fullscreen mode

awk prints lines 3 through 7.


🔄 Solution 3: Using head and tail

The task can also be solved using head and tail.

#!/bin/bash

if [ $# -ne 3 ]
then
    echo "Usage: $0 <file> <start_line> <end_line>"
    exit 1
fi

file=$1
a1=$2
a2=$3

if [ ! -f "$file" ]
then
    echo "Error: File does not exist."
    exit 1
fi

if ! [[ "$a1" =~ ^[1-9][0-9]*$ ]] || ! [[ "$a2" =~ ^[1-9][0-9]*$ ]]
then
    echo "Error: Line numbers must be positive integers."
    exit 1
fi

if [ "$a1" -gt "$a2" ]
then
    echo "Error: Invalid line range."
    exit 1
fi

count=$((a2 - a1 + 1))

head -n "$a2" "$file" | tail -n "$count"
Enter fullscreen mode Exit fullscreen mode

How It Works

Suppose:

a1 = 3
a2 = 7
Enter fullscreen mode Exit fullscreen mode

First:

head -n 7 marks.txt
Enter fullscreen mode Exit fullscreen mode

gets the first 7 lines.

Then:

tail -n 5
Enter fullscreen mode Exit fullscreen mode

gets the last 5 lines of those 7 lines.

Therefore, the result is:

Lines 3, 4, 5, 6, 7
Enter fullscreen mode Exit fullscreen mode

📊 Comparing the Solutions

Method Main Command Difficulty Recommended
Solution 1 sed ⭐⭐ ✅ Best
Solution 2 awk ⭐⭐⭐ ✅ Good
Solution 3 head + tail ⭐⭐ Alternative

Which Solution Should You Use?

For this practical, sed is the cleanest solution because it directly supports displaying a specific range of lines.

If your syllabus focuses on awk, the second solution is useful.

The head + tail approach is good for understanding how multiple Linux commands can be combined using a pipeline.


🧠 Important Concepts Used

Command-Line Arguments

$1
$2
$3
$#
Enter fullscreen mode Exit fullscreen mode

File Tests

-f
-r
Enter fullscreen mode Exit fullscreen mode

Numeric Comparison

-gt
Enter fullscreen mode Exit fullscreen mode

Regular Expression Validation

[[ "$value" =~ regex ]]
Enter fullscreen mode Exit fullscreen mode

Line Processing

sed
awk
head
tail
Enter fullscreen mode Exit fullscreen mode

Command Substitution

total_lines=$(wc -l < "$file")
Enter fullscreen mode Exit fullscreen mode

⚠️ Common Mistakes

Mistake 1: Forgetting Argument Validation

Don't directly use:

file=$1
a1=$2
a2=$3
Enter fullscreen mode Exit fullscreen mode

without checking $#.

Always make sure the required arguments are provided.


Mistake 2: Not Checking the File

Before reading the file, check:

[ -f "$file" ]
Enter fullscreen mode Exit fullscreen mode

and preferably:

[ -r "$file" ]
Enter fullscreen mode Exit fullscreen mode

Mistake 3: Allowing Invalid Line Numbers

Values such as:

abc
-5
2.5
Enter fullscreen mode Exit fullscreen mode

should not be accepted as line numbers.


Mistake 4: Invalid Range

This is invalid:

a1 = 10
a2 = 5
Enter fullscreen mode Exit fullscreen mode

because the starting line comes after the ending line.


Mistake 5: Forgetting Quotes Around File Names

Prefer:

sed -n "${a1},${a2}p" "$file"
Enter fullscreen mode Exit fullscreen mode

instead of:

sed -n "${a1},${a2}p" $file
Enter fullscreen mode Exit fullscreen mode

Quoting helps when the file name contains spaces or special characters.


🎯 Practical Exam Tips

Remember this basic command:

sed -n '3,7p' marks.txt
Enter fullscreen mode Exit fullscreen mode

It displays lines 3 to 7.

For command-line arguments:

$1 → File
$2 → Starting line
$3 → Ending line
Enter fullscreen mode Exit fullscreen mode

For argument count:

$#
Enter fullscreen mode Exit fullscreen mode

For file validation:

[ -f "$file" ]
Enter fullscreen mode Exit fullscreen mode

For readable file:

[ -r "$file" ]
Enter fullscreen mode Exit fullscreen mode

For positive integer validation:

[[ "$num" =~ ^[1-9][0-9]*$ ]]
Enter fullscreen mode Exit fullscreen mode

📚 Related Linux Practical Sets

This solution is part of the VNSGU TYBCA Sem 5 Linux (UNIX) Practical – OCT/Nov 2025 solution series.

  • Set A – Simple Interest & Compound Interest
  • Set B – Vowels Count & Case Conversion
  • Set C – Palindrome String
  • Set D – File Operations & Text Processing
  • Set E – Display Lines with Validation
  • Set F – Count Files & Directories
  • Set G – Recently Modified Files
  • Set H – Employee Gross Salary

🐧 Conclusion

Set E is an excellent practical for learning command-line arguments and input validation.

The main logic is:

Validate arguments
      ↓
Validate file
      ↓
Validate line numbers
      ↓
Validate line range
      ↓
Display required lines
Enter fullscreen mode Exit fullscreen mode

Among the different approaches, sed provides the most direct solution for displaying a range of lines.

Practice the validation carefully because the question specifically mentions:

Proper validation required.


💬 What Do You Prefer?

For displaying a range of lines from a file, which approach do you prefer?

sed, awk, or head + tail?

Share your approach in the comments! 🐧💻


📌 Tags

linux shell unix beginners

Top comments (0)