Kintarō Kintarō - 2 months ago 7
Bash Question

How to loop through a list in shell?

Suppose I have a command which outputs a list of strings

string1
string2
string3
.
.
stringN


How can I loop through the output of the list in a shell?

For example:

myVal=myCmd
for val in myVal
do
# do some stuff
end


(I am very new to shell programming...)

Answer

Use a bash while-loop, the loop can be done over a command or an input file.

while IFS= read -r string
do 
    some_stuff to do
done < <(command_that_produces_string)

With an example, I have a sample file with contents as

$ cat file
My
name
is not 
relevant
here

I have modified the script to echo the line as it reads through the file

$ cat script.sh
#!/bin/bash
while IFS= read -r string
do
    echo "$string"
done < file

produces an o/p when run as ./script.sh

My
name
is not
relevant
here

The same can also be done over a bash-command, where we adopt process-substitution (<()) to run the command on the sub-shell.

#!/bin/bash

while IFS= read -r -d '' file; do
    echo "$file"
done < <(find . -maxdepth 1 -mindepth 1 -name "*.txt" -type f -print0)

The above simple find lists all files from the current directory (including ones with spaces/special-characters). Here, the output of find command is fed to stdin which is parsed by while-loop.