Shell Script To Display Last Five Lines Of The File

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
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.