Loops
Looping Over Lines in a Variable String
list="One\ntwo\nthree\nfour"
while IFS= read -r line; do
echo "$line"
done <<< "$list"
# or
echo "$list" | while IFS= read -r line; do
echo "$line"
done
# or
for line in $(echo ${list}); do
echo "$line"
done
For variables with literal string
echo -e "$list" | while IFS= read -r line; do
echo "$line"
done
Ref:
Looping Over Filtered File Path Returned by Find
Method 1:
find . -name '*.txt' - print0 |
while IFS= read -r -d '' file; do
# do something with "$file"
done
NOTE: Each command of a pipeline is executed in a separate subshell. So variables outside of the loop that are modified inside of the subshell will not change the value of the variables outside.
Method 2: (Recommended)
while IFS= read -r -d '' file; do
# do something with "$file"
done < <(find . -name '*.txt' - print0)
This method allows for variable modification outside of the loop. See process substitution.
Ref:
- 📄 How to loop through file names returned by find?: Method 1 reference
- 📄 How to loop through file names returned by find?: Method 2 reference
- 📄 Variables disappearing after loop in a pipeline terminates