Working with a List of Tuples in Shell Scripting

Several people have recently asked me whether or not it is possible to use tuples in their shell script. One example is running a program with a varying set of parameters. Since they often did not find a good solution, they began to formulate their problem in a higher-level scripting language like Ruby. Surprisingly, you can accomplish the same task easily with simple shell scripting (supported by bash, zsh,..). Consider the following (semi-stupid) example

paramset="foo.txt 1 --with-graphics
bar.txt 8 --no-graphics
flock.txt 4 --with-graphics"

echo "$du" | while read file p1 p2 ; do
./myProgram $file -t $p1 --verbose $p2

We here run the program myProgram three times (for each line in the multi-line string). Every line contains three white-space separated values (words), to which we assign the variable names file, p1, p2 in the loop header. Note that the last variable (in this case p2) always contains all remaining words of a given line if there are more words then variables.

The set of parameters can also be stored in a file. In that case, replace the loop header with cat params.txt | while read file p1 p2 ; do. If the script is not working properly, examine the Input-Field-Separator (IFS) variable, which should be set to IFS=" ".

One Response to “Working with a List of Tuples in Shell Scripting”

  1. That’s a great! The script should read:

    echo “$paramset” | while #etc…

    rather than

    echo “$du” | while #etc…