Reading File Line by Line in Linux Shell Script

Channel: Linux
Abstract: - Some times we required to read file content line by line inside shell a script. For this example this script will read /etc/passwd file line by line
While Loop: while read line
do
echo $line
done < /tmp/file.txt

Note: 「line」 is a variable which contains a single line read from file.

Example:-

Some times we required to read file content line by line inside shell a script. For this example this script will read /etc/passwd file line by line and print usernames with there corresponding home directory.

#!/bin/bash

while read line
do
    USERNAME=`echo $line | cut -d":" -f1`
    HOMEDIR=`echo $line | cut -d":" -f6`
    echo "$USERNAME =>  $HOMEDIR"
done < /etc/passwd

Ref From: tecadmin

Related articles