Main menu:

Taoyuan Nights

A cute, kludgey coding trick.

Today, a student told me she had to run a series of tests on pictures, with particular filenames… for example, files numbered 13, 17, 21, 23, and so on.

So, I explained that in BASH, we can do this quite easily:

for i in 13 17 21 23 ; do
commandname $i
done

However, she explained that each of these pictures has a corresponding data value that has to be entered, and that doesn’t relate to the picture directly. For example, 13 might have the value 93, 17 might have the value 90, 21 might have the value 99 and so on. We need to enter these tuples in order to write the script.

Now, you could set up some list, and iterate through it, but it’s a nightmare if you want to add or delete a value, because you need to make sure your two lists don’t accidentally get out of sync as you add or remove numbers from them.

Unlike PERL, I don’t believe BASH has sufficiently complex data types that you could pass (13,93) as a single value. So… here’s a quick and ugly way to do this in a single loop without using a more complex datatype.

for i in 1393 1790 2199 2389 ; do
$a=$((i/100))
$b=$((i%100))
commandname $a $b
done

In a situation where names are needed rather than numbers, you could use “firstpart-lastpart” style items in the for loop declaration, and then use the regular expression features built into BASH to split it apart as you iterate.

So, what’s the advantage of doing things this way? It’s easy to remember and you can code it in about 5 seconds flat.

The disadvantages? Read an article about Strong typing!

Related articles