Categories
Linux Tips & Tutorials

How to read a file line by line in bash script using while loop

This tutorial introduces the concept of playing a file line by line in bash script using while loop.

PREREQUISITES

This tutorial assumes that the reader has basic knowledge of bash scripting & programming skills.

STEPS

  • First of all create a script file. For example touch looptest.sh
  • In root directory we have a one file name of readline.txt
  • Now this script read line by line of readline.txt file and echo the content of the file line by line

[​[email protected]mylinuxtips.info ~]# cat readline.txt

This is line 1

This is line 2

This is line 3

This is line 4

  • Create the script now

[[email protected]mylinuxtips.info ~]# cat looptest.sh

#!/bin/bash

FILE="/root/readline.txt"

# The while loop remains the most appropriate and easiest way to read a file line by line.

while read line

do

echo ${line}

sleep 1

done < ${FILE}

  • Its time to execute this script. To execute a file we need to give executable permissions on it.​

[[email protected] ~]# chmod +x looptest.sh

[[email protected]mylinuxtips.info~]# ./looptest.sh

[[email protected]mylinuxtips.info ~]# This is line 1

[[email protected]mylinuxtips.info ~]# This is line 2

[[email protected]mylinuxtips.info ~]# This is line 3

[[email protected]mylinuxtips.info ~]# This is line 4

 

By Sushant Chawla

Over the past 11 years I have acquired very good knowledge of:

- Cloud Setup on Amazon, Rackspace with autoscaling, load balancers, etc
- LAMP architecture
- LNMP Architecture
- Apache, Nginx, Lighttpd
- Databases: MySQL and PostgreSQL
- Bash Scripting
- Configuration Management with Puppet
- Monitoring: Nagios, Zabbix, ICINGA
- Mail servers: Sendmail, Postfix, Exim
- Web Accelerators & Caching Setups with Memcache, Varnish & Redis
- Setup and Management of high availability applications clusters
- LDAP, Samba, NFS, FTP, DNS, DHCP, Openfire, Squid Proxy
- Subversion(SVN), GIT
- Control Panels: Plesk, Webmin, cPanel

Apart from Linux, I am a great sports star & regular traveller. I like working out and exploring various places.

Cheers ;-)