If you come from a developer background or have dabbled in programming, you will have (probably) come across the term array. If we needed to explain arrays in a single sentence, it would look like this: Arrays allow us to store a collection of data of the same type. To make this a little less abstract, we'll show you how we can create an array of strings in Bash:
reader@ubuntu:~$ array=("This" "is" "an" "array")
reader@ubuntu:~$ echo ${array[0]}
This
reader@ubuntu:~$ echo ${array[1]}
is
reader@ubuntu:~$ echo ${array[2]}
an
reader@ubuntu:~$ echo ${array[3]}
array
In this string array, we place four elements:
- This
- is
- an
- array
If we want to print the string in the first place in the array, we need to specify that we want the zeroth position with the echo ${array[0]} syntax. Remember, as is common in IT, the first item in a list is often found at the 0th position. Now, look at what happens if we try to grab the fourth position, and thus the fifth value (that is not there):
reader@ubuntu:~$ echo ${array[4]}
# <- Nothing is printed here.
reader@ubuntu:~$ echo $?
0
reader@ubuntu:~$ echo ${array[*]}
This is an array
Weirdly enough, even though we're asking for the value in a position of the array that does not exist, Bash does not consider this an error. If you did the same in some programming languages, such as Java, you'd see an error akin to ArrayIndexOutOfBoundsException. As you can see after the exit status of 0, if we want to print all the values in the array, we use the asterisk (as a wildcard).
In our scripting example, to keep it a little simpler, we've used whitespace delimited strings when we needed to create a list (for reference, look at the script for-simple.sh from Chapter 11, Conditional Testing and Scripting Loops again). In our experience, for most purposes, this is often easier to work with and powerful enough. Should this not seem the case for your scripting challenges, however, remember that such a thing as arrays in Bash exist and that, perhaps, these might work for you.