How do I create an array in unix shell scripting?
Array in Unix is a data structure consisting of a collection of elements stored in a memory location which is contiguous, whose data type can be the same or different like integer, strings, etc. and they are referenced by the index beginning with zero.
Array in Shell Scripting An array is a systematic arrangement of the same type of data. But in Shell script Array is a variable which contains multiple values may be of same type or different type since by default in shell script everything is treated as a string. An array is zero-based ie indexing start with 0.
There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.
Access Array Elements Similar to other programming languages, Bash array elements can be accessed using index number starts from 0 then 1,2,3…n. This will work with the associative array which index numbers are numeric. To print all elements of an Array using @ or * instead of the specific index number.
The following code creates and prints an array of strings in shell:
#!/bin/bash array=("A" "B" "ElementC" "ElementE") for element in "${array[@]}" do echo "$element" done echo echo "Number of elements: ${#array[@]}" echo echo "${array[@]}"
Result:
A B ElementC ElementE Number of elements: 4 A B ElementC ElementE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With