How to write a bash shell script to read a file line by line. Here is sample bash shell script ,which will when executed will read an input file line by line.

The above script contains file name sample.txt

How it works

  • The shell variable filepath is assigned path of the file to be read.
  • The shell variable IFS_OLD is assigned default value of IFS ( internal filed separator ). To read more about IFS follow the link http://wikistack.com/internal-field-separator-shell-script/
  • The next statement “for line in $(cat $filepath ) will read each line in shell variable line and print each line by do and done loop.
  • In the last line export IFS=$OLD_IFS is done , which is assigning default value of IFS again.

How to run the script

  • Save the above script as sample.sh
  • Run “chmod +x sample.sh” command. This will make sample.sh executable.
  • Run the script in terminal, like below.

terminal@#./sample.sh

Write a bash shell script to read a file line by line

Here is simple video tutorial, Write a bash shell script to read a file line by line.