I've always had trouble getting `for` loops to work predictably, so my common loop pattern is this: grep -l -r pattern /path/to/files | while read x; do echo $x; done
or the like.This uses bash read to split the input line into words, then each word can be accessed in the loop with variable `$x`. Pipe friendly and doesn't use a subshell so no unexpected scoping issues. It also doesn't require futzing around with arrays or the like. One place I do use bash for loops is when iterating over args, e.g. if you create a bash function: function my_func() {
for arg; do
echo $arg
done
}
This'll take a list of arguments and echo each on a separate line. Useful if you need a function that does some operation against a list of files, for example.Also, bash expansions (https://www.gnu.org/software/bash/manual/html_node/Shell-Par...) can save you a ton of time for various common operations on variables. |
Here's what it can look like. Some functions I wrote to bulk-process git repos. Notice they accept arguments and stdin:
Source: https://github.com/adityaathalye/bash-toolkit/blob/master/bu...The best part is sourcing pipeline-friendly functions into a shell session allows me to mix-and-match them with regular unix tools.
Overall, I believe (and my code will betray it) functional programming style is a pretty fine way to live in shell!