Shell Script To Display Last Five Lines Of The File

in Categories Academic last updated April 12, 2008

Given the filename by the user as the input, write a shell script to display the last five lines of the file.

Shell Script

#!/bin/bash
# get filename
echo -n "Enter File Name : "
read fileName
 
# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists"
  exit 1
fi
 
# display last five lines of the file using tail command
tail -5 $fileName

Command Line Argument

You can read file name as command line argument:

#!/bin/bash
# get filename
fileName="$1"
# make sure command line arg provided 
if [ -z $1 ]; then
	echo "Syntax: $(basename $0) filename"
	exit 1
fi
# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists"
  exit 1
fi
# ok display last five lines of the file using tail command
tail -5 $fileName