The Ultimate Bash Array Tutorial with 15 Examples


/ Published in: Bash
Save to your folder(s)



Copy this code and paste it in your HTML
  1.  
  2. by SASIKALA on JUNE 3, 2010
  3. An array is a variable containing multiple values may be of same type or of different type. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Array index starts with zero.
  4.  
  5. In this article, let us review 15 various array operations in bash.
  6.  
  7. This article is part of the on-going Bash Tutorial series. For those who are new to bash scripting, get a jump-start from the Bash Scripting Introduction tutorial.
  8.  
  9. 1. Declaring an Array and Assigning values
  10.  
  11. In bash, array is created automatically when a variable is used in the format like,
  12.  
  13. name[index]=value
  14. name is any name for an array
  15. index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.
  16. $ cat arraymanip.sh
  17. #! /bin/bash
  18. Unix[0]='Debian'
  19. Unix[1]='Red hat'
  20. Unix[2]='Ubuntu'
  21. Unix[3]='Suse'
  22.  
  23. echo ${Unix[1]}
  24.  
  25. $./arraymanip.sh
  26. Red hat
  27. To access an element from an array use curly brackets like ${name[index]}.
  28.  
  29. 2. Initializing an array during declaration
  30.  
  31. Instead of initializing an each element of an array separately, you can declare and initialize an array by specifying the list of elements (separated by white space) with in a curly braces.
  32.  
  33. Syntax:
  34. declare -a arrayname=(element1 element2 element3)
  35. If the elements has the white space character, enclose it with in a quotes.
  36.  
  37. #! /bin/bash
  38. $cat arraymanip.sh
  39. declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');
  40. declare -a declares an array and all the elements in the parentheses are the elements of an array.
  41.  
  42.  
  43.  
  44. 3. Print the Whole Bash Array
  45.  
  46. There are different ways to print the whole elements of the array. If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash.
  47.  
  48. echo ${Unix[@]}
  49.  
  50. # Add the above echo statement into the arraymanip.sh
  51. #./t.sh
  52. Debian Red hat Ubuntu Suse
  53. Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero.
  54.  
  55. 4. Length of the Bash Array
  56.  
  57. We can get the length of an array using the special parameter called $#.
  58.  
  59. ${#arrayname[@]} gives you the length of the array.
  60.  
  61. $ cat arraymanip.sh
  62. declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora');
  63. echo ${#Unix[@]} #Number of elements in the array
  64. echo ${#Unix} #Number of characters in the first element of the array.i.e Debian
  65. $./arraymanip.sh
  66. 4
  67. 6
  68. 5. Length of the nth Element in an Array
  69.  
  70. ${#arrayname[n]} should give the length of the nth element in an array.
  71.  
  72. $cat arraymanip.sh
  73. #! /bin/bash
  74.  
  75. Unix[0]='Debian'
  76. Unix[1]='Red hat'
  77. Unix[2]='Ubuntu'
  78. Unix[3]='Suse'
  79.  
  80. echo ${#Unix[3]} # length of the element located at index 3 i.e Suse
  81.  
  82. $./arraymanip.sh
  83. 4
  84. 6. Extraction by offset and length for an array
  85.  
  86. The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.
  87.  
  88. $cat arraymanip.sh
  89. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  90. echo ${Unix[@]:3:2}
  91.  
  92. $./arraymanip.sh
  93. Suse Fedora
  94. The above example returns the elements in the 3rd index and fourth index. Index always starts with zero.
  95.  
  96. 7. Extraction with offset and length, for a particular element of an array
  97.  
  98. To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array.
  99.  
  100. $cat arraymanip.sh
  101. #! /bin/bash
  102.  
  103. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  104. echo ${Unix[2]:0:4}
  105.  
  106. ./arraymanip.sh
  107. Ubun
  108. The above example extracts the first four characters from the 2nd indexed element of an array.
  109.  
  110. 8. Search and Replace in an array elements
  111.  
  112. The following example, searches for Ubuntu in an array elements, and replace the same with the word ‘SCO Unix’.
  113.  
  114. $cat arraymanip.sh
  115. #!/bin/bash
  116. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  117.  
  118. echo ${Unix[@]/Ubuntu/SCO Unix}
  119.  
  120. $./arraymanip.sh
  121. Debian Red hat SCO Unix Suse Fedora UTS OpenLinux
  122. In this example, it replaces the element in the 2nd index ‘Ubuntu’ with ‘SCO Unix’. But this example will not permanently replace the array content.
  123.  
  124. 9. Add an element to an existing Bash Array
  125.  
  126. The following example shows the way to add an element to the existing array.
  127.  
  128. $cat arraymanip.sh
  129. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  130. Unix=("${Unix[@]}" "AIX" "HP-UX")
  131. echo ${Unix[7]}
  132.  
  133. $./arraymanip.sh
  134. AIX
  135. In the array called Unix, the elements ‘AIX’ and ‘HP-UX’ are added in 7th and 8th index respectively.
  136.  
  137. 10. Remove an Element from an Array
  138.  
  139. unset is used to remove an element from an array.unset will have the same effect as assigning null to an element.
  140.  
  141. $cat arraymanip.sh
  142. #!/bin/bash
  143. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  144.  
  145. unset Unix[3]
  146. echo ${Unix[3]}
  147. The above script will just print null which is the value available in the 3rd index. The following example shows one of the way to remove an element completely from an array.
  148.  
  149. $ cat arraymanip.sh
  150. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  151. pos=3
  152. Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})
  153. echo ${Unix[@]}
  154.  
  155. $./arraymanip.sh
  156. Debian Red hat Ubuntu Fedora UTS OpenLinux
  157. In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index. And merge both the above output. This is one of the workaround to remove an element from an array.
  158.  
  159. 11. Remove Bash Array Elements using Patterns
  160.  
  161. In the search condition you can give the patterns, and stores the remaining element to an another array as shown below.
  162.  
  163. $ cat arraymanip.sh
  164. #!/bin/bash
  165. declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
  166. declare -a patter=( ${Unix[@]/Red*/} )
  167. echo ${patter[@]}
  168.  
  169. $ ./arraymanip.sh
  170. Debian Ubuntu Suse Fedora
  171. The above example removes the elements which has the patter Red*.
  172.  
  173. 12. Copying an Array
  174.  
  175. Expand the array elements and store that into a new array as shown below.
  176.  
  177. #!/bin/bash
  178. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  179. Linux=("${Unix[@]}")
  180. echo ${Linux[@]}
  181.  
  182. $ ./arraymanip.sh
  183. Debian Red hat Ubuntu Fedora UTS OpenLinux
  184. 13. Concatenation of two Bash Arrays
  185.  
  186. Expand the elements of the two arrays and assign it to the new array.
  187.  
  188. $cat arraymanip.sh
  189. #!/bin/bash
  190. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  191. Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
  192.  
  193. UnixShell=("${Unix[@]}" "${Shell[@]}")
  194. echo ${UnixShell[@]}
  195. echo ${#UnixShell[@]}
  196.  
  197. $ ./arraymanip.sh
  198. Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh ksh rc tcsh
  199. 14
  200. It prints the array which has the elements of the both the array ‘Unix’ and ‘Shell’, and number of elements of the new array is 14.
  201.  
  202. 14. Deleting an Entire Array
  203.  
  204. unset is used to delete an entire array.
  205.  
  206. $cat arraymanip.sh
  207. #!/bin/bash
  208. Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  209. Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
  210.  
  211. UnixShell=("${Unix[@]}" "${Shell[@]}")
  212. unset UnixShell
  213. echo ${#UnixShell[@]}
  214.  
  215. $ ./arraymanip.sh
  216. 0
  217. After unset an array, its length would be zero as shown above.
  218.  
  219. 15. Load Content of a File into an Array
  220.  
  221. You can load the content of the file line by line into an array.
  222.  
  223. #Example file
  224. $ cat logfile
  225. Welcome
  226. to
  227. thegeekstuff
  228. Linux
  229. Unix
  230.  
  231. $ cat loadcontent.sh
  232. #!/bin/bash
  233. filecontent=( `cat "logfile" `)
  234.  
  235. for t in "${filecontent[@]}"
  236. do
  237. echo $t
  238. done
  239. echo "Read file content!"
  240.  
  241. $ ./loadcontent.sh
  242. Welcome
  243. to
  244. thegeekstuff
  245. Linux
  246. Unix
  247. Read file content!
  248. In the above example, each index of an array element has printed through for loop.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.