Author : Piyush Gupta
You can use while..do to read file line by line on a Linux or Unix-like system.
You can use while..do to read file line by line on a Linux or Unix-like system.
Syntax: Read file line by line on a Bash Unix & Linux shell:
- The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
- while read -r line; do COMMAND; done < input.file
- The -r option passed to read command prevents backslash escapes from being interpreted.
- Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed –
- while IFS= read -r line; do COMMAND_on $line; done < input.file
Example:-
How to Read a File Line By Line in Bash
Here is more human readable syntax for you:
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.