An array in shell scripting is a data structure that allows the storage of multiple values under a single variable name. Arrays help organize and manipulate data efficiently, making them a fundamental concept in shell scripting.
Declaring an Array
To declare an array in shell scripting, you can use the following syntax:
array_name=(value1 value2 value3 ..)
For example, let’s declare an array named “fruits” containing some popular fruits:
fruits=("apple" "banana" "orange")
Accessing Array Elements
You can access individual elements of an array using their index. The index starts from 0 for the first element and increments by 1 for each subsequent element. To retrieve the value at a specific index, use the following syntax:
${array_name[index]}
For instance, to access the second element of the “fruits” array declared earlier (i.e., “banana”), use:
${fruits[1]}
Looping through Array Elements
Shell scripting provides various ways to loop through array elements. One common method is using the for
loop combined with the ${#array_name[@]}
construct, which returns the length (number of elements) of an array. Here’s an example that demonstrates this technique:
for ((i=0; i<${#fruits[@]}; i++)) do echo ${fruits[i]} done
Modifying Array Elements
To modify an existing element in an array, simply assign a new value to that element’s index. For example, to change the third element (“orange”) in our “fruits” array to “kiwi,” use:
fruits[2]="kiwi"
Appending New Elements to an Array
You can append new elements to an array using the +=
operator. Here’s an example:
fruits+=("grape" "pineapple")
After executing this code, the “fruits” array will contain “apple,” “banana,” “kiwi,” “grape,” and “pineapple.”
Deleting Array Elements
To delete a specific element from an array, use the unset
command followed by the element’s index. For instance, to remove the second element (“banana”) from our “fruits” array, use:
unset fruits[1]
Array Length
To determine the length of an array (i., the number of elements), you can use the ${#array_name[@]}
construct. For example:
length=${#fruits[@]} echo $length
In summary, arrays in shell scripting provide a convenient way to store and manipulate multiple values under a single variable name. With proper understanding and utilization of arrays, you can efficiently manage complex data structures in your shell scripts.