Unix - Using Arrays

Arrays in Unix are used to store and manipulate data in a collection of elements. The basic syntax for declaring an array in Unix is:

array_name=(element1 element2 element3 ...)

 

To access a specific element of the array, you need to specify the index of that element, starting with 0. For example, to access the second element of the array, you would use:

${array_name[1]}

 

To print all the elements of the array, you can use the following syntax:

echo ${array_name[*]}

 

To loop through all the elements of an array, you can use a for loop. For example:

for i in ${array_name[@]}; do

echo $i

done

 

You can also use an associative array in Unix, which is similar to a regular array but uses a string as the index instead of a number. The syntax for declaring an associative array is:

declare -A assoc_array_name

assoc_array_name=([key1]=value1 [key2]=value2 ...)

 

To access a specific element of an associative array, you need to specify the key, like this:

${assoc_array_name[key1]}

 

Arrays are commonly used in Unix scripts to store and process data in a structured way. They can be used for a variety of purposes, such as storing command line arguments, processing data from files, or storing output from commands.