Arrays in unix shell? Arrays in unix shell? unix unix

Arrays in unix shell?


The following code creates and prints an array of strings in shell:

#!/bin/basharray=("A" "B" "ElementC" "ElementE")for element in "${array[@]}"do    echo "$element"doneechoecho "Number of elements: ${#array[@]}"echoecho "${array[@]}"

Result:

ABElementCElementENumber of elements: 4A B ElementC ElementE


in bash, you create array like this

arr=(one two three)

to call the elements

$ echo "${arr[0]}"one$ echo "${arr[2]}"three

to ask for user input, you can use read

read -p "Enter your choice: " choice


Bourne shell doesn't support arrays. However, there are two ways to handle the issue.

Use positional shell parameters $1, $2, etc.:

$ set one two three$ echo $*one two three$ echo $#3$ echo $2two

Use variable evaluations:

$ n=1 ; eval a$n="one" $ n=2 ; eval a$n="two" $ n=3 ; eval a$n="three"$ n=2$ eval echo \$a$ntwo