WCC logo

CIS120Linux Fundementals

Arrays

Arrays in Bash scripting are a powerful way to store and manage multiple pieces of related data. Think of an array as a collection of items, like a list of favorite songs or the names of your friends. Each item in the array has a specific position or "index" that lets you access it quickly. In Bash, arrays are easy to create and work with, and they can store strings, numbers, or a combination of both.

To create an array in Bash, you simply assign values using parentheses. For example, let’s create an array of fruits:

fruits=("apple" "banana" "cherry" "date")

In this example, the array fruits contains four items. The first item is "apple," the second is "banana," and so on. In programming, arrays are zero-indexed, which means the first item is at position 0, the second at position 1, and so forth. So, if we want to access "banana," we would use index 1, like this:

echo ${fruits[1]}

This command will output "banana." You can access any element in an array by using the array name followed by the index in square brackets, with a dollar sign before it.

You can also change an item in the array by specifying its index and giving it a new value. Suppose we want to change "date" to "dragonfruit." We’d do it like this:

fruits[3]="dragonfruit"

Now, if we print the entire array, "date" is replaced with "dragonfruit." To print all the items in an array at once, use the following command:

echo ${fruits[@]}

This will print out all the items: "apple banana cherry dragonfruit." The [@] symbol lets Bash know we want to access all elements.

Sometimes, you’ll need to know the total number of items in an array. Bash provides an easy way to do this by using ${#arrayname[@]}. For example:

echo ${#fruits[@]}

This command will output 4, showing there are four items in the fruits array.

Finally, you might want to loop through each item in an array to process them one by one. You can do this with a for loop like so:

for fruit in "${fruits[@]}"
do
  echo "I love $fruit"
done

This loop goes through each item in the fruits array and prints out "I love apple," "I love banana," and so on. Loops like this are handy when you want to perform the same action on each item in an array.

Arrays in Bash make it easy to handle lists of related data, and as you practice, you’ll find they can help simplify and organize your scripts.