Bash read file line by line

I use bash to read file line by line on a Linux system. The content Bash read file line by line. Bash script the essential for DevOps Roles. you can ref to Bash script tutorial.

To read a file line by line using Bash, you can use a combination of the while loop and the read command.

Examples Bash read file line by line

Example 1: Using bash to read file.txt file.

[huupv@huupv devopsroles]$ cat file.txt 
Huu 30
Phan 28
foo 00

The content file

#To take a filename as an argument
while read -r name age
  echo "Name read from file - ${_NAME}"
  echo "${_NAME}: Age is - ${_AGE}"
done < "$filename"

To change mode execute and run the bash script

[huupv@huupv devopsroles]$ chmod +x
[huupv@huupv devopsroles]$ ./ file.txt

The screen terminal:

Name read from file - Huu
Huu: Age is - 30
Name read from file - Phan
Phan: Age is - 28
Name read from file - foo
foo: Age is - 00

Example 2: Bash script read /etc/passwd file with fields: filed1 filed2 filed3 filed4 filed5 filed6 filed7

The content file

#Another thing is to take a filename as an argument.
while read -r field1 field2 field3 field4 field5 field6 field7
  #display fields in /etc/passwd file
  printf 'Username: %s \t Shell: %s \t Home Dir: %s\n' "$field1" "$field7" "$field6"

done < "$filename"

The while loop reads each line from the file using the read command. The IFS= read -r field command ensures that leading and trailing whitespaces are preserved in each line.

The screen output terminal:

Bash read file line by line


Thought the article, you can use Bash read file line by line. I hope will this your helpful.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.