Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays in unix shell?

How do I create an array in unix shell scripting?

like image 780
Arunachalam Avatar asked Dec 10 '09 05:12

Arunachalam


People also ask

What are arrays in Unix?

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.

What is array in shell?

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.

Are there arrays in shell script?

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.

How do you access an array in bash?

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.


1 Answers

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 
like image 115
Vincent Agami Avatar answered Oct 04 '22 12:10

Vincent Agami