This is a multipart blog article series where I am going to explain the concepts of shell scripting and how to write a shell script in Linux, UNIX or Mac based systems. You can also follow this tutorial blog using windows but for that you have to install a bash from.
In this article we will see various ways by which we can read the content of a file using while loop and shell script.
The first method is like this.
- Here we use
- This means that the content of the file will be sent to the
while loop and then we will store the value of while loop
inside a variable and then print the content of that
variable line by line.
shell while read <variable_name> do echo $<variable_name> done < <file_name>
- Here we use
Second way is like this.
- Here the output of the cat command is the input of the
shell cat <file_name> | while read <variable_name> do echo $<variable_name> done
- Here the output of the cat command is the input of the while command. -
The third way to do the same thing is like this.
- We cannot use the above methods in some cases, than we use the IFS methods.
- Here we are assigning space to IFS.
- We use
-rbecause with the help of this it will do not interpret backslash. -
shell while IFS='' read -r <variable_name> do echo $<variable_name> done < <file_name>
At the place of file we can also give the file present at different location, along with their address just like this
So this was all about the different ways by which we can read the content of the file using while loop in a shell script. Hope you liked it and learned something new form it.
If you have any doubt, question, quires related to this topic or just want to share something with me, than please feel free to contact me.