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

[​root@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

[root@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

[root@mylinuxtips.info~]# ./looptest.sh

[root@mylinuxtips.info ~]# This is line 1

[root@mylinuxtips.info ~]# This is line 2

[root@mylinuxtips.info ~]# This is line 3

[root@mylinuxtips.info ~]# This is line 4