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
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.
You are very close, can't tell if it is just cut and paste/typos that are causing the issue - note the quotes on line 1 and the $ in line 2.
myVal=`echo "a b c"`
for val in $myVal
do
echo "$val"
done
a b c and a, b and c on three different lines.* with a list of files in the current directory.* being expanded by the in $myVal has a result that itself can be treated as a glob, that'll happen again in echo $val do to the lack of quotes there.