| 1 | #!/bin/bash |
| 2 | # array-function.sh: Passing an array to a function and ... |
| 3 | # "returning" an array from a function |
| 4 | |
| 5 | |
| 6 | Pass_Array () |
| 7 | { |
| 8 | local passed_array # Local variable! |
| 9 | passed_array=( `echo "$1"` ) |
| 10 | echo "${passed_array[@]}" |
| 11 | # List all the elements of the new array |
| 12 | #+ declared and set within the function. |
| 13 | } |
| 14 | |
| 15 | |
| 16 | original_array=( element1 element2 element3 element4 element5 ) |
| 17 | |
| 18 | echo |
| 19 | echo "original_array = ${original_array[@]}" |
| 20 | # List all elements of original array. |
| 21 | |
| 22 | |
| 23 | # This is the trick that permits passing an array to a function. |
| 24 | # ********************************** |
| 25 | argument=`echo ${original_array[@]}` |
| 26 | # ********************************** |
| 27 | # Pack a variable |
| 28 | #+ with all the space-separated elements of the original array. |
| 29 | # |
| 30 | # Attempting to just pass the array itself will not work. |
| 31 | |
| 32 | |
| 33 | # This is the trick that allows grabbing an array as a "return value". |
| 34 | # ***************************************** |
| 35 | returned_array=( `Pass_Array "$argument"` ) |
| 36 | # ***************************************** |
| 37 | # Assign 'echoed' output of function to array variable. |
| 38 | |
| 39 | echo "returned_array = ${returned_array[@]}" |
| 40 | |
| 41 | echo "=============================================================" |
| 42 | |
| 43 | # Now, try it again, |
| 44 | #+ attempting to access (list) the array from outside the function. |
| 45 | Pass_Array "$argument" |
| 46 | |
| 47 | # The function itself lists the array, but ... |
| 48 | #+ accessing the array from outside the function is forbidden. |
| 49 | echo "Passed array (within function) = ${passed_array[@]}" |
| 50 | # NULL VALUE since the array is a variable local to the function. |
| 51 | |
| 52 | echo |
| 53 | |
| 54 | ############################################ |
| 55 | |
| 56 | # And here is an even more explicit example: |
| 57 | |
| 58 | ret_array () |
| 59 | { |
| 60 | for element in {11..20} |
| 61 | do |
| 62 | echo "$element " # Echo individual elements |
| 63 | done #+ of what will be assembled into an array. |
| 64 | } |
| 65 | |
| 66 | arr=( $(ret_array) ) # Assemble into array. |
| 67 | |
| 68 | echo "Capturing array \"arr\" from function ret_array () ..." |
| 69 | echo "Third element of array \"arr\" is ${arr[2]}." # 13 (zero-indexed) |
| 70 | echo -n "Entire array is: " |
| 71 | echo ${arr[@]} # 11 12 13 14 15 16 17 18 19 20 |
| 72 | |
| 73 | echo |
| 74 | |
| 75 | exit 0 |
| 76 | |
| 77 | # Nathan Coulter points out that passing arrays with elements containing |
| 78 | #+ whitespace breaks this example. |