| 1 | #!/bin/bash |
| 2 | # array-ops.sh: More fun with arrays. |
| 3 | |
| 4 | |
| 5 | array=( zero one two three four five ) |
| 6 | # Element 0 1 2 3 4 5 |
| 7 | |
| 8 | echo ${array[0]} # zero |
| 9 | echo ${array:0} # zero |
| 10 | # Parameter expansion of first element, |
| 11 | #+ starting at position # 0 (1st character). |
| 12 | echo ${array:1} # ero |
| 13 | # Parameter expansion of first element, |
| 14 | #+ starting at position # 1 (2nd character). |
| 15 | |
| 16 | echo "--------------" |
| 17 | |
| 18 | echo ${#array[0]} # 4 |
| 19 | # Length of first element of array. |
| 20 | echo ${#array} # 4 |
| 21 | # Length of first element of array. |
| 22 | # (Alternate notation) |
| 23 | |
| 24 | echo ${#array[1]} # 3 |
| 25 | # Length of second element of array. |
| 26 | # Arrays in Bash have zero-based indexing. |
| 27 | |
| 28 | echo ${#array[*]} # 6 |
| 29 | # Number of elements in array. |
| 30 | echo ${#array[@]} # 6 |
| 31 | # Number of elements in array. |
| 32 | |
| 33 | echo "--------------" |
| 34 | |
| 35 | array2=( [0]="first element" [1]="second element" [3]="fourth element" ) |
| 36 | # ^ ^ ^ ^ ^ ^ ^ ^ ^ |
| 37 | # Quoting permits embedding whitespace within individual array elements. |
| 38 | |
| 39 | echo ${array2[0]} # first element |
| 40 | echo ${array2[1]} # second element |
| 41 | echo ${array2[2]} # |
| 42 | # Skipped in initialization, and therefore null. |
| 43 | echo ${array2[3]} # fourth element |
| 44 | echo ${#array2[0]} # 13 (length of first element) |
| 45 | echo ${#array2[*]} # 3 (number of elements in array) |
| 46 | |
| 47 | exit |