Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jul 9, 2024
Difficulty: Easy

Array variables in Shell Scripting

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hey Ninjas! You must hear about the Linux OS if you are a software DevOps. If you are a Linux user, then it is obvious that you have used Shell Scripting. A shell script is a list of commands in a computer program run by the Unix shell, a command line interpreter.

Shell Scripting - Array variables

In this blog, we will discuss the Array variables in Shell Scripting.

Array Variables in Shell Scripting

An array is a variable that can store values of the same data types. Each value in an array is indexed starting from index 0 for the first value. It is almost similar to Shell Script but with a slight difference. The difference between an array and a Shell Script array is that it supports values of all data types. The reason is Shell Script treats everything as a single string.

We can use two types of arrays in the shell script.

Associative Arrays: It contains Elements with key-value pairs.

Indexed Arrays: It contains Indexed Elements starting with zero.

Also, there are three types of declaration in the Shell Scripting.

Explicit Declaration: Here, we declare the array and assign value to them. 

For example,

declare -a arrayName

 

Compound Assignment: Here, we declare the array along with the values.

For example,

arrayName=(v1 v2 v3 .... vN)

 

Indirect Declaration: Here, we only assign value to a specific index.

For example,

arrrayName[indexNumber]=value
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working with Array in Shell Scripting

First, let's understand how to create an array using Shell Scripting. 

Syntax:

arrayName[subscript] = value

 

Example:

declare -a myArray
myArray[0]=value

OR

declare -A myArray
myArray[key]=value

 

Notice a lowercase "a" in the first line used to declare an indexed array. Also, there is a capital "A" in the next example. This is used to declare an associative array.

Accessing Array Elements

As we know, we can access the array elements that are being indexed individually. We can access all the elements by specifying the array index as shown below:

myArray[element]="Hey Ninjas"
echo ${myArray[element]}

 

Output

Hey Ninjas

 

The above given is an example of Associate Arrays. Let's now check out the indexed array example.

myArray=(1 2 3 4 5)
echo ${myArray[2]}

 

Output

3

Reading Array Elements

We will use the loop concept here. It will be very easy if you are already familiar with the loop concepts.

myArray=(1 2 3 4 5 6 7 8)

for i in ${myArray[@]}
do
    echo $i
done

 

Output

1
2
3
4
5
6
7
8

 

Here, You must have thought about what myArray[@] is. So, the [@] symbol is used to print all the elements at the same time.

Note that we can perform the same using the [*] symbol. 

Now, we will check how to print elements from a specific index. Let's see the syntax first.

echo ${arrrayName[whichElement]:startingIndex}

 

We are now moving toward an example of the same.

myArray=(I really love Coding Ninjas)
echo ${myArray[@]:0}     
echo ${myArray[@]:1}
echo ${myArray[@]:2}     
echo ${myArray[0]:1} 

 

Output:

Output

The last line echo ${myArray[0]:1} will not print anything as the 0th element (I) does not have enough characters to print.

We can also print the element within any given range. Let's understand this using an example.

The syntax says:

echo ${arrayName[whichElement]:startingIndex:countElement}

 

Example:

myArray=(I really love Coding Ninjas)
echo ${myArray[@]:1:4}     
echo ${myArray[@]:2:3} 
echo ${myArray[@]:3:4}     
echo ${myArray[0]:1:3} 

 

Output:

Output

The reason for not printing the output for the echo ${myArray[0]:1:3} line is the same. The 0th element (I) does not have enough characters to print.

Counting the Number of Elements

There is a symbol similar to @, #. This # symbol is used to get the count of the elements in the given array. Let's test this using an example.

myArray=(1 2 3 4 5)
echo ${#myArray[@]}

 

Output:

5

Delete a Single Array Element

The "unset" keyword is used to delete any specific element in an array. We just have to give the array name and the index of the element that we wish to remove. Let's check this out using an example.

myArray=(1 2 3 4 5 6 7 8)
printf "Array before delete:\n"
for i in ${myArray[@]}
do
    echo $i
done
unset myArray[2]
printf "Array after delete:\n"
for i in ${myArray[@]}
do
    echo $i
done

 

Output:

Array before delete:
1
2
3
4
5
6
7
8
Array after delete:
1
2
4
5
6
7
8

Search and Replace Array Element

Now we will learn how to search and replace an array element or any character in an array. Let's take an example for better understanding.

Syntax:

echo ${arrayName[@]//character/replacement}

 

Example:

myArr=(My fav learning website is Coding Ninjas)
echo ${myArr[@]//fav/favourite}   #changing a complete element
echo ${myArr[@]//d/D}                   #changing a character in an element

 

Output:

Output
Check out this problem - Maximum Product Subarray

Frequently Asked Questions

What is the N in a shell script?

You can use the \n character instead of repeatedly echoing to start new lines in your shell script. For Unix-based systems, the \n is a newline character that helps move the commands that follow it to a new line.

Is string empty bash?

To check if a string is empty in Bash, we can make an equality check with a given string and empty the string using the string equal-to = operator. The other way is to use the -z string operator to check if the size of the given string operand is zero. 

What is the Bash test?

A test in bash is not a test of the function of your app. It is a way of showing a statement that may or may not be true. You can use tests in bash to put conditional commands into practice. They contain what is being tested in square brackets, i.e., [and].

Conclusion

This article discusses the topic of Array variables in Shell Scripting. In detail, we have seen the Array variables in Shell Scripting, working with an array in the shell script, including accessing, reading, counting, and deleting using array elements.

We hope this blog has helped you enhance your knowledge of Array variables in Shell Scripting. If you want to learn more, then check out our articles.

Shell Scripting - Arithmetic Operations.

Shell Scripting Interview Question.

Linux - Shell Variables.

Array in Javascript

And many more on our platform Coding Ninjas Studio.

 

Recommended problems -

 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio.

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Topics covered
1.
Introduction
2.
Array Variables in Shell Scripting
3.
Working with Array in Shell Scripting
3.1.
Accessing Array Elements
3.2.
Reading Array Elements
3.3.
Counting the Number of Elements
3.4.
Delete a Single Array Element
3.5.
Search and Replace Array Element
4.
Frequently Asked Questions
4.1.
What is the N in a shell script?
4.2.
Is string empty bash?
4.3.
What is the Bash test?
5.
Conclusion