It seems nearly every week, I find something amazingly handy in bash that I had not used before. This time: Loops. I would bet nearly everyone who has written more than a handful of shell scripts over a few lines in length has used one or more of the loops bash has to offer. But, what I realized (not sure why it did not bash me sooner) is that loops are also very effective timesavers as one-off commands in everyday shell usage.
I suppose the association came from first using the shell in a very simple way, of just giving commands singly, and only using constructs like loops in scripts I wrote out in files. But recently, I had several identical operations to perform on a series of files with consistent names, and a loop came to mind. The files were all mp4 videos, and I needed to convert them with ffmpeg, and send them through flvtool2. Instead of 2 commands typed out for each file, I ran:
1 2 3 4 5 6 7 | for FILE in $(find . -maxdepth 1 -type f -iname \*large.mp4); do ffmpeg -sameq -i $FILE -s 480x270 -ar 44100 -r 10 $FILE.flv; done for FILE in $(find . -maxdepth 1 -type f -iname \*.flv); do cat $FILE | flvtool2 -U stdin $FILE; done |
To simply iterate over a list of strings, using each in a command:
1 2 3 | for TABLE in cool_table1 cool_table2 cool_table3; do mysqldump -u root cool_database $TABLE; done |
You can use loops like this in any shell script, just write the whole loop on one line, separating the conditions, parts in the suite, and the termination with semicolons (these are mostly optional when using line breaks in scripts in files). Assorted resources:
- Post that inspired me, with lots of practical tips for loop usage.
- More advanced loop documentation from TLDP.
- Post with helpful examples
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.








