When writing scripts that perform the same task over and over again with different parameters, it is tempting to just cut and paste. Here’s an example of a bash script:


#!/usr/bin/env bash
grunt make_magic --dir=/foo
grunt make_magic --dir=/bar
grunt make_magic --dir=/lorem
grunt make_magic --dir=/ipsum
grunt make_magic --dir=/magnum
...

Imagine that goes on for hundreds of directories!

This isn’t very DRY. If we wanted to add an extra parameter to the grunt command, we’d have a lot of editing to do.

If we needed to do another command on those very same directories, we would have to enter the directory names again. As you can see, it would be very easy to forget to add all of them.

DRY

DRY stands for “Don’t Repeat Yourself”. If some code or commands are duplicated elsewhere, that’s a sign that there are inefficiencies in the code.

The idea behind this is to pull out common code into functions/methods. When a change to that code is required, it only needs to be made once. If a bug is identified in the code, once it is fixed, it is fixed “everywhere”.

DRYing

Let’s take the example above and dry it up. We have to run the same command with different parameters (directories), so we will create an array of directories:

DIRS=( foo bar lorem ipsum magnum )

Now we write a “for…each” loop to do something for each element in the array:


for thedir in "${DIRS[@]}"; do
grunt make_magic --dir=/$thedir
done

This works on each element of the DIRS array and assigns it to thedir variable, which is now available inside the block.

Using this technique, it is very easy to add additional commands and/or directories.