Looping on variable having new line \n fails

I have a for loop that constructs a variable "filelistonly" having entries separated by "\n" new line.

The second, third & fourth while loops are my attempt to iterate the variable "filelistonly" upon new line "\n", however non of them work.

Below is my script:

//First Loop
for i in $(echo $1 | tr ',' '\n')
do
    fileresult=`find $i -name hello.db -type f`
    filelistonly=$filelistonly`echo ${fileresult%:*}`"\n"
done

//Second Loop
while read -r line; do
echo "*** $line ***"
done <<< "$filelistonly"

//Third Loop
while read line; do
echo line="$line";
done < <(echo "$filelistonly" | tr ',' '\n')

//Fourth Loop
while read -r line; do
    if [ $line != "\n" ]; then
           echo "We are Good. $line File Found."
    else
        echo "New Line Found.... Ignoring"
    fi
done <<< "$filelistonly"

Below is the debug Output:

The below code works and resolves the new line problem reported above however the if condition fails which is shown in debug below.

    filelistonly=$filelistonly`echo ${fileresult%:*}`$'\n'

Output showing if condition failing.....

I guess the issue could be in the first loop where I'm constructing the variable "filelistonly", however I'm not sure of a solution yet.

try: if [ "$line" != "\n" ] in case $line is an empty string.

1 Like

You can simplify your loops by controlling the special IFS variable. The shell itself can be told to split on newlines and only newlines, or on commas, or quotes, or whatever.

OLDIFS="$IFS"
# Yes, looks funny, but its a single newline in double-quotes
IFS="
"
STR="string
containing lots of
newlines and
stuff"

for X in $STR
do
        echo "X is $X"
done

# Restore normal splitting behavior
IFS="$OLDIFS"

Also, some of those echoes look redundant.

filelistonly="${filelistonly}${fileresult%:*}\n"

...and most of those \n's in your code aren't real newlines:

$ echo "\n"

\n

$

So I suspect a lot of your code isn't doing what you think it is.