Chapter 7. List and Hash Handling

Computers, as we know, are very good at counting and organizing data. We can use code to count and organize data by using a data structure, and the building blocks for those are arrays. Bash has had arrays since the beginning and added associative arrays in version 4.0. You will run into hard-to-read code for bash arrays out there, partly because bash has a lot of history and backward compatibility to maintain, as we mentioned earlier, but also because some developers tend to overcomplicate things. Arrays are actually not that hard to implement, and you can write about them clearly with a little thought.

As a refresher, in computer science and programming, arrays are variables containing multiple elements that are indexed or referred to by an integer. Or in other words, an array is a variable containing a list instead of a scalar or single value. An associative array is a type of list that is indexed by a string instead of an integer. So it’s a list of key-value pairs, that basically forms a dictionary or look-up table, where internally the key is hashed to form a memory location. More or less.

The bash documentation uses the terms array and associative arrays, but depending on your background, lists and hashes, or possibly dictionaries or dicts, may be more familiar, and they are certainly easier to type and say. The bash documentation also uses subscript where other people might say index. We usually follow the bash docs for consistency, but ...

Get bash Idioms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.