Shell scripting: Iterate over a list line-by-line instead of word-by-word

Let’s say a directory contains these files:

My First File.txt
My Second File.txt

If you wanted to take an action on each distinct file, you might try something like this:

for file in `ls ~`; do echo $file; done

The output will look like below, because the spaces and line breaks are both treated delineators of a new item in the list (ie. a new assignment to the “file” variable.)

My 
First
File.txt
My
Second
File.txt

If your intent was to act on the complete filename (using only line breaks as indicators of a new item) then you can instead pipe your output through a “while” loop like this:

ls ~ | while read item; do echo $item; done

Which will yield the desired output:

My First File.txt
My Second File.txt