Predictive Hacks

Arrays in Bash

This tutorial is a brief introduction to arrays in bash. Data Scientists are familiar with arrays, in R, a simple array is called “vector” and in Python is called “list”.

How to Create an Array

There are many different ways to create arrays in Bash, but in this example, we will show you one of the many by creating a simple array called “mynames” containing the elements “John”, “Bob” and “Maria”.

declare -a mynames=(John Bob Maria)

Note that each element is white space separated, the elements are within a parenthesis and there is no extra space around the equal sign.

How to Retrieve Array Elements

The indexing of the arrays in bash starts from 0. If we want to retrieve the 2nd element of the array, which corresponds to index 1, we can run:

echo ${mynames[1]}
Bob

Thus, we can get each element by entering its index within the square brackets.

If we want to print all the elements, we have to add the “@” within the square brackets, like:

echo ${mynames[@]}
John Bob Maria

Keep in mind that we can get the same results by using the “*” instead of the “@”.

echo ${mynames[*]}
John Bob Maria

How to Add Elements

We can add an element by specifying the index and the element. For example, let’s add “George” to the array.

mynames[3]=George
echo ${mynames[@]}
John Bob Maria George

We can append one or more elements to the array using the “+=”, like:

mynames+=(Jim Helen)
echo ${mynames[@]}
John Bob Maria George Jim Helen

How to Update Elements

We can update the content of the elements by overwriting them, like:

mynames[3]=Jason
echo ${mynames[@]}
John Bob Maria Jason Jim Helen

As we can see, we replaced “George”, with “Jason”.

How to Delete Elements

We can use the “unset” command to delete an element of an array. Let’s say that we want to remove “Helen”.

unset mynames[5]
echo ${mynames[@]}
John Bob Maria Jason Jim

How to Get the Length of an Array

We can get the length of an array, i.e. the number of elements, by running:

echo ${#mynames[@]} 
5

As we expected, the length of the array is 5.

How to Iterate over an Array

We can iterate over an array by running:

for i in ${mynames[*]}
do
    echo $i
done

How to Delete an Array

We can delete the array by running:

unset mynames

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s