While Loop with Shell
I think most developers immediately think in terms of a for loop first. In fact, the Go language foregoes using separate loop syntax altogether and instead uses a very flexible for loop statement. In shell land, I would argue that the while loop is a much more useful tool when banging out quick maintenance tasks. Why? Pipes. You can encapsulate filtering for a for loop statement by interpolating one command inside another, but it’s not nearly as clean to grok. If you’re running multiple loops in a one liner (in the real world that does happen some times), flowing linearly through pipes can help reasoning about an operation. Consider the following:
ls | grep -V foo | sed 's/\./-/g' | sort -u | while read line; do
\ blah $line; doneCould this be done with a for loop? Absolutely. Would it make as much sense? Nope. Shell coding practices not only don’t follow permanent coding conventions, they shouldn’t. When you write throw away code, or need to get tasks done quickly, trying to be proper is a red herring. It gains you nothing and costs you time; possibly during critical production situations, and that’s the one thing you can’t spare.