For loops in bash

Iteration: it’s such a powerful tool. Automating the repetition of tasks can save so much time and keystrokes and tedium. This capability is one of the reasons I love bash, my command shell of choice. I used to employ tcsh, but switched to bash years ago mainly because most linux system scripts use bash, and I wanted to just focus on one syntax so that my own scripts and the system ones would be equally readable. But bash also opened my eyes to the beauties of command-line for loops. (Tcsh makes them interactive, which initially seems nice, but then is annoying if you’d like to re-do an earlier loop you typed in.)

So now I regularly use for loops at the command line for all sorts of things: resizing a collection of images, creating a collection of symbolic links, renaming a series of files by some standard convention. It’s great for any task in which you want to do the same operation, but the individual commands differ slightly, and in which you can’t just pass in a wildcard list of inputs. But for the longest time, I thought there was only one form of the loop syntax:

for i in choice1 choice2 … choiceN ; do
… [some task with $i, the current choice]
done

Thanks to this great collection of for loop examples, I’ve learned that bash now also supports sequence iteration! So you can do

for i in {1..5}; do
… [some task with $i, a number from 1 to 5] …
done

Previously, I would have written

for i in 1 2 3 4 5 ; do
… [some task with $i, the current choice] …
done

which gets very clunky with larger ranges, involving nested loops, one per digit. Ugh!

Newer bashes (version 4.0+) even support increments, e.g.

for i in {1..5..2}; do
… [some task with $i, an odd number from 1 to 5] …
done

And wow, there’s even a C-style syntax:

for (( i=1; i<=5; i++ )); do
… [some task with $i, a number from 1 to 5] …
done

For loops just got easier.

I used this today to generate a file that contained 16 1’s followed by 16 2’s followed by 16 3’s… all the way up to 16 30’s. Exactly the kind of thing I don’t want to do manually. And yes, I actually needed this file in order to get some research done. So it goes!