Arrays in unix shell?

How to create an array in unix shell scripts?

+73
arrays unix bash shell
Dec 10 '09 at 5:55
source share
14 answers

The following code creates and prints an array of strings in the 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 AB ElementC ElementE 
+82
Sep 19 '13 at 15:21
source share

in bash you create an array like this

 arr=(one two three) 

call items

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

to request user input you can use read

 read -p "Enter your choice: " choice 
+57
Dec 10 '09 at 6:25
source share

The Bourne shell does not support arrays. However, there are two ways to solve the problem.

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

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

Use variable estimates:

 $ n=1 ; eval a$n="one" $ n=2 ; eval a$n="two" $ n=3 ; eval a$n="three" $ n=2 $ eval echo \$a$n two 
+16
Mar 13 '13 at 0:24
source share
 #!/bin/bash # define a array, space to separate every item foo=(foo1 foo2) # access echo "${foo[1]}" # add or changes foo[0]=bar foo[2]=cat foo[1000]=also_OK 

You can read the ABS "Advanced Bash-Scripting Guide"

+13
Dec 10 '09 at 6:18
source share

The Bourne shell and the C shell have no arrays, IIRC.

In addition to what others said, in Bash you can get the number of elements in an array as follows:

 elements=${#arrayname[@]} 

and perform slice style operations:

 arrayname=(apple banana cherry) echo ${arrayname[@]:1} # yields "banana cherry" echo ${arrayname[@]: -1} # yields "cherry" echo ${arrayname[${#arrayname[@]}-1]} # yields "cherry" echo ${arrayname[@]:0:2} # yields "apple banana" echo ${arrayname[@]:1:1} # yields "banana" 
+8
Dec 10 '09 at 8:00
source share

Try this:

 echo "Find the Largest Number and Smallest Number of a given number" echo "---------------------------------------------------------------------------------" echo "Enter the number" read n i=0 while [ $n -gt 0 ] #For Seperating digits and Stored into array "x" do x[$i]='expr $n % 10' n='expr $n / 10' i='expr $i + 1' done echo "Array values ${x[@]}" # For displaying array elements len=${#x[*]} # it returns the array length for (( i=0; i<len; i++ )) # For Sorting array elements using Bubble sort do for (( j=i+1; j<len; j++ )) do if [ 'echo "${x[$i]} > ${x[$j]}"|bc' ] then t=${x[$i]} t=${x[$i]} x[$i]=${x[$j]} x[$j]=$t fi done done echo "Array values ${x[*]}" # Displaying of Sorted Array for (( i=len-1; i>=0; i-- )) # Form largest number do a='echo $a \* 10 + ${x[$i]}|bc' done echo "Largest Number is : $a" l=$a #Largest number s=0 while [ $a -gt 0 ] # Reversing of number, We get Smallest number do r='expr $a % 10' s='echo "$s * 10 + $r"|bc' a='expr $a / 10' done echo "Smallest Number is : $s" #Smallest Number echo "Difference between Largest number and Smallest number" echo "==========================================" Diff='expr $l - $s' echo "Result is : $Diff" echo "If you try it, We can get it" 
+7
Mar 14 '12 at 8:23
source share

Your question is about "Unix shell scripts," but tagged as bash . These are two different answers.

The POSIX shell specification has nothing to do with arrays, as the original Bourne shell did not support them. Even today on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh does not support an array. Therefore, if you want your script to work in different Bourne-compatible shells, you should not use them. Alternatively, if you are proposing a specific shell, be sure to include its full name in the shebang line, for example #!/usr/bin/env bash .

If you are using bash or zsh or a modern version of ksh , you can create an array as follows:

 myArray=(first "second element" 3rd) 

and access such items

 $ echo "${myArray[1]}" second element 

You can get all the items through "${myArray[@]}" . You can use the slice notation $ {array [@]: start: length} to limit the part of the array referenced, for example, "${myArray[@]:1}" to skip the first element.

The length of the array is ${#myArray[@]} . You can get a new array containing all indexes from an existing array using "${!myArray[@]}" .

Older versions of ksh prior to ksh93 also had arrays, but not parenthesized notations, nor did they support slicing. You can create an array as follows:

 set -A myArray -- first "second element" 3rd 
+6
Dec 09 '15 at 16:24
source share

You can try the following type:

 #!/bin/bash declare -a arr i=0 j=0 for dir in $(find /home/rmajeti/programs -type d) do arr[i]=$dir i=$((i+1)) done while [ $j -lt $i ] do echo ${arr[$j]} j=$((j+1)) done 
+5
Dec 10 '09 at 6:06
source share

An array can be loaded in twoways.

 set -A TEST_ARRAY alpha beta gamma 

or

 X=0 # Initialize counter to zero. 

- Load an array with the lines alpha, beta and gamma

 for ELEMENT in alpha gamma beta do TEST_ARRAY[$X]=$ELEMENT ((X = X + 1)) done 

In addition, I think the below information may help:

The shell supports one-dimensional arrays. The maximum number of elements array is 1024. When an array is defined, it is automatically up to 1024 elements in size. A one-dimensional array contains a sequence of array elements that look like connected boxers together on a train.

If you want to access the array:

 echo ${MY_ARRAY[2] # Show the third array element gamma echo ${MY_ARRAY[*] # Show all array elements - alpha beta gamma echo ${MY_ARRAY[@] # Show all array elements - alpha beta gamma echo ${#MY_ARRAY[*]} # Show the total number of array elements - 3 echo ${#MY_ARRAY[@]} # Show the total number of array elements - 3 echo ${MY_ARRAY} # Show array element 0 (the first element) - alpha 
+5
Jul 20 '15 at 14:33
source share

If you want the white space key value store to use the -A option:

 declare -A programCollection programCollection["xwininfo"]="to aquire information about the target window." for program in ${!programCollection[@]} do echo "The program ${program} is used ${programCollection[${program}]}" done 

http://linux.die.net/man/1/bash "Associative arrays are created using the -A name declaration."

+4
Apr 18 '15 at 20:18
source share

To read values โ€‹โ€‹from keybord and insert an element into an array

 # enter 0 when exit the insert element echo "Enter the numbers" read n while [ $n -ne 0 ] do x[$i]=`expr $n` read n let i++ done #display the all array elements echo "Array values ${x[@]}" echo "Array values ${x[*]}" # To find the array length length=${#x[*]} echo $length 
+3
Aug 05 '13 at 5:59 on
source share

There are several ways to create an array in the shell.

 ARR[0]="ABC" ARR[1]="BCD" echo ${ARR[*]} 

${ARR[*]} prints all the elements in the array.

The second way is:

 ARR=("A" "B" "C" "D" 5 7 "J") echo ${#ARR[@]} echo ${ARR[0]} 

${#ARR[@]} used to calculate the length of the array.

+3
Sep 14 '18 at 11:57
source share

In ksh you do this:

 set -A array element1 element2 elementn # view the first element echo ${array[0]} # Amount elements (You have to substitute 1) echo ${#array[*]} # show last element echo ${array[ $(( ${#array[*]} - 1 )) ]} 
+1
Dec 10 '09 at 17:37
source share

A simple way:

 arr=("sharlock" "bomkesh" "feluda" ) ##declare array len=${#arr[*]} #determine length of array # iterate with for loop for (( i=0; i<len; i++ )) do echo ${arr[$i]} done 
+1
Sep 02 '18 at 15:40
source share



All Articles