How to iterate over lines in a variable in Bash?

while IFS= read -r line; do
    echo "... $line ..."
done <<< "$list"
echo $output | while read line ; do
   echo === $line ===
done

For some reason the methods above echo out a empty line. the method below does’nt

IFS=$'\n' 
for line in $output; do
  echo ${line};
done

IFS Variable and Its Default Values

The special shell variable IFS determines how Bash recognizes word boundaries while splitting a sequence of character strings. The default value of IFS is a three-character string comprising a space, tab, and newline:

$ echo "$IFS" | cat -et
 ^I$
$

Here we used the -e and -t options of the cat command to display the special character values of the IFS variable.

Now, Let’s run an example to demonstrate word splitting on a space-delimited string:

$ string="foo bar foobar"
$ for i in $string
> do
>  echo "'$i' is the substring"
> done
'foo' is the substring 
'bar' is the substring
'foobar' is the substring

As we looped over the string, we could get the individual substring because space is one of the IFS variable’s default values.

Leave a Reply

Your email address will not be published.