Note: The second part of this series can be found here.

For many years I have feared and avoided shell scripting. Perhaps my comfort zone was rooted in compiled languages. You might even say I’ve lived a very SHELLtered life until now fucking lol. In any case, lately I’ve faced my fear and come to realise what an incredible tool the shell can be.

This post is the first of several in which I’m noting down cool stuff that I didn’t know was possible in Bash. I’m going to focus on Bash rather than other shells because that’s what I use.

One of the things I learned recently was that Bash handles arrays just like “proper” languages, both in terms of declaration and language constructs for accessing their elements and iterating over them.

Declaring and Iterating over an array

Here is an example of how to create an array and print its elements to stdout:

#!/bin/bash
some_things=(apple banana orange)

for thing in "${some_things[@]}"; do
  echo "${thing}"
done

Which outputs:

apple
banana
orange

Lovely. What else can you do? Turns out LOADS.

### Array length & individual element access

#!/bin/bash
some_things=(apple banana orange)

echo "array length is ${#some_things[@]}"
echo "element 2 is ${some_things[1]}"

Which outputs:

array length is 3
element 2 is banana

### Adding to arrays

How about adding to arrays?

#!/bin/bash
some_things=(apple banana orange)
echo "array length is ${#some_things[@]}"

some_things[${#some_things[*]}]="pear"
echo "array length is ${#some_things[@]}"
echo "element 4 is ${some_things[3]}"

Which outputs:

array length is 3
array length is 4
element 4 is pear

Conclusions

For all that, it’s not necessarily appropriate in many shell situations because piping commands is arguably simpler and more effective. However it is without doubt a powerful tool to consider when composing scripts, and these examples barely scratch the surface.