How to Declare Array in Shell Scripting?

Arrays can be declared in a shell script using various approaches:

1. Indirect Declaration

In this method, you assign a value to a specific index of the array variable. There’s no need to declare the array beforehand.

ARRAYNAME[INDEXNR]=value

2. Explicit Declaration

With explicit declaration, you first declare the array and then assign values to it.

declare -a ARRAYNAME

3. Compound Assignment

This method involves declaring the array along with its initial set of values. You can later add additional values to the array.

ARRAYNAME=(value1 value2  .... valueN)

Alternatively, you can use index numbers to assign values explicitly:

ARRAYNAME=([1]=10 [2]=20 [3]=30)

Array Basics in Shell Scripting | Set 1

Consider a situation if we want to store 1000 numbers and perform operations on them. If we use a simple variable concept then we have to create 1000 variables and perform operations on them. But it is difficult to handle a large number of variables. So, it is good to store the same type of values in the array and then access via index number.

Similar Reads

Understanding Arrays in Shell Scripting

An array is a structured arrangement of similar data elements. Within shell scripting, an array is a variable that holds multiple values, whether they are of the same type or different types. It’s important to note that in shell scripting, everything is treated as a string. Arrays adhere to a zero-based index, which signifies that indexing initiates from 0....

How to Declare Array in Shell Scripting?

Arrays can be declared in a shell script using various approaches:...

Printing Array Values in Shell Script:

To display array elements, you have several options:...

Conclusion

In this article we discussed about utility of arrays in shell scripting. It underlines how arrays efficiently handle a multitude of values, replacing numerous variables. The concept of array declaration is explained through three methods: indirect, explicit, and compound assignment. The article further illustrates printing array elements using practical script examples. This discussion not only demystifies array usage but also underscores its significance in managing and manipulating data within shell scripts....