"For line" is interpreted as "for word"?

Does anyone know how to use a for loop to loop through every line in a file? I've tried googling but the answers i find online seem to be incorrect.

Supposedly you can loop through each line in a file by doing:

#!/bin/bash
declare -i count=1
file=$(cat file.txt)
for line in $file
 do
  echo "line $count is $line"
  let "count++"
done
exit

But when I do that it loops through every word instead and says "line n is word".

Anyone know why this does not work, and why people online say it does?

Posted in: s/bash

๐Ÿš€ asdf

Feb 20 ยท 5 months ago

1 Comment

๐Ÿš€ clseibold ยท Feb 20 at 18:04:

Yeah, that doesn't work for me either. I don't know who or why someone said it does. The "line" in the script you're using is just a variable name, and so has no semantic meaning outside of what you give it. Bash for loops loop on *all* whitespace, so the script will only work if lines don't have any spaces in them.

You can use this instead:

while IFS= read -r line; do
    echo "$line"
done < filename.txt

Setting IFS to nothing will tell the `read` command to read by line rather than by word.


Source