How to loop or iterate through the output of ls command in a bash script
If your original purpose is to iterate through the list of files and directories present in the current directory, you don’t even have to run ls command for that.
for i in *; do echo "$i" done
Alternately you can use ls to get the list of files and directories as shown below.
for i in `ls`; do echo "$i" done
Other way of writing the above example is:
for i in $(ls); do echo "$i"; done;
The ls command can be used to select files of certain pattern. The following example selects only files will extension “.sh”.
for i in $(ls *.sh); do echo "$i"; done;


about 2 years ago
One can pipe the multi-lined output to “xargs” command to convert in to single line of output.
find . -iname \*.sh | xargs
The above example recursively finds all files with .sh extension. Combine the above example with the example mentioned in the article.
for i in $(find . -iname \*.sh | xargs); do echo “$i”; done;