How to read line by line from file in bash script?

I searched online about this problem, and so far I have found two ways:

while read line; do commands done < "$filename" 

and

  for $line in $(cat $filename); do commands done 

none of them work if the lines have a space, for example, if we have such a line

  textextext text 

it will not print textextext text

but

  textextext text 

he considers these things to be another line, how can I avoid this?

+4
source share
2 answers

Like this?

 while IFS= read line ; do something "$line" done <"$file" 

Here is a quick test:

 while IFS= read line ; do echo "$line"; done <<<"$(echo -e "ab\nc d")" ab cd 
+9
source

You can read (bash 4+)

 readarray lines < "$file" 

then

 for line in "${lines[@]}"; do echo "$line" done 

Note that by default readarray will even contain a line readarray character for each line

+6
source

All Articles