How To Loop Through Lines in a File in Bash?

Often you may want to loop through each line from a file and do something to each line. Yes, you can use Python or other programming language to do that.

However, a simple bash script can be extremely useful in looping through lines in a file. Here is how to loop through lines in a file using bash script.

Let us say the name of the file that we want to loop through is stored in a variable in bash.

filname=loop_thru_line_in_bash.txt

In bash, we can access the content of variable using $ sign as a prefix to the variable name. For example, we can print the name of the file using echo command.

echo $filename

If the file is not big, we can store all lines of the file in to a variable using cat command. cat command followed by the file name will show all the lines.

all_lines=`cat $filename`

To loop through each line, we can use for loop. The basic structure of for loop in bash is this

for item in $my_list;
do
  echo $item
done

Using the similar format, we can loop through each line of the file. Here, we simply print each line

for line in $file_lines ; 
do
    echo $line
done