Search code examples
bashshellparsingnewlineifs

Read command is parsing multiline input


The read command in the below code is parsing only the first line from the input. But it works fine when the IFS is set to comma or any other symbol other than newline.

u="*
john
dan"

IFS=$'\n';read -ra q <<< "$u"

for j in "${q[@]}"
do
    echo "drop user $j"
done

The output is just:

drop user *

What I'm expecting is:

drop user *
drop user john
drop user dan

Note that the first item in the input is an asterisk. So if I use the below code for splitting, then the asterisk gets expanded to the list of files in the directory.

IFS=$'\n'; q=($u); unset IFS;

Output:

drop user abc
drop user test.sh
drop user john
drop user dan

What is wrong with the above code? How to correct it to get the intended output?


Solution

  • You can just do this while read loop:

    u="*
    john
    dan"
    while IFS= read -r user; do
        echo "drop user $user"
    done <<< "$u"
    

    Output:

    drop user *
    drop user john
    drop user dan