Loop over tuples in Bash

In Software Engineering, Snippet

I’ve found the cleanest way to loop over a list of tuples to be

With this pattern, an array of elems (consisting of tuples separated by a space) is declared. Then for each tuple, items are read into another array strarr. This works because the the default Internal Field Separator (IFS) is a space, tab, and newline. These items can then be accessed from this new array. Note that the tuples don’t all need to be the same size.

Of course, a different IFS can be used. In the past, I’ve used the “set-then-reset” pattern, which temporarily sets a new IFS, say, to a comma for comma-delimited lines. Additionally, set -- ${tuple} can be used to set positional parameters to be separated.

However this can be avoided by simply setting IFS inside the loop, which may be easier to read and safer to handle (i.e. by preventing the need to “reset” the IFS back to an “old” value again).

References

One Comment

Marc 2022-07-18 Reply

Hello!
many thanks for your post!

Leave a Reply