Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read line by line using `for` loop

How can I read line by line using for loop?

what I've tried:

hh=$(echo -e "\n1\n2\n3\n4\n")

IFS=$'\n';

for r in "$hh"; do echo $r; done
1 2 3 4

echo -e "$hh"

1
2
3
4
like image 612
Orlo Avatar asked Apr 30 '26 02:04

Orlo


2 Answers

Use a while loop:

$ while read -r r; do echo $r; done <<< "$hh"

1
2
3
4
like image 167
devnull Avatar answered May 02 '26 20:05

devnull


The correct answer is, you don't read line-by-line with a for loop. Use a while loop instead with the read builtin:

while IFS= read -r line; do
    echo "$line"
done <<< "$hh"
like image 25
chepner Avatar answered May 02 '26 19:05

chepner