Objective: Read the contents of a file line by line in a shell script.
The following block of code will read a file (referenced by variable $input_file
) line by line from top to bottom and store the contents of the currently read line into a variable called $line
. In the input file, each line has to be terminated by a newline (‘\n’) character.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/bin/sh # path to input file input_file=/path/to/input/file # read file line by line and store in $line while IFS="" read -r line do # do whatever you want to do with the currently read line here echo "read from file: $line" done < "$input_file" |
The variable IFS
is set to an empty string to prevent the read
command from removing the leading and trailing whitespace characters.
The “-r
” option to read
command makes sure that it will not interpret backslash as an escape character.