Simple Bash Loop Constructs

Many times it is useful to write an ad-hoc program within bash to accomplish a task. Most of an ad-hoc script is composed of text formatting as well as a loop to get things running. The most useful loop structure that I find in my experience is a do while loop as follows:

bash$ ls | while read line; do cat $line; done >out.txt

As can be seen from this command line, most of the heavy lifting is performed within the while loop.  This while loop will perform the given command on each line that is input into the construct and your bash command can further redirect its output to a file or a command that follows.  You may notice this construct in many of the bash one-liners that I post here in the future.  xargs can usually be used to perform repeated tasks as well, however I find that this chain of commands is more flexible.

No Comments Posted in bash
Tagged ,