Last active
May 29, 2018 05:13
-
-
Save jimratliff/da46854f32ec9f4d39c9c1864761fc5f to your computer and use it in GitHub Desktop.
Example: Pass array to bash function with command substitution #bash #bash_exemplar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Context: | |
Pass array to function, where one or more elements of the array have embedded spaces. | |
Moreover, script seeks a nonnumeric result from function; uses command substitution to call the function. | |
For the case without command substitution, see https://gist.github.com/jimratliff/ddcb5eb7e6fb184840e5dfd7e240c7ee | |
Goal: Have the embedded spaces respected in the array processed by the function. | |
############### The script | |
#!/usr/bin/env bash | |
set -eu | |
function echo_passed_array() { | |
list_of_options=("$@") | |
echo "List of options [0]: ${list_of_options[0]}" > /dev/tty | |
echo "List of options [1]: ${list_of_options[1]}" > /dev/tty | |
echo "List of options [2]: ${list_of_options[2]}" > /dev/tty | |
echo "${list_of_options[1]}" | |
return 0 | |
} | |
# Main | |
two_word_element="Maybe someday" | |
declare -a available_options | |
available_options[0]="Yes" | |
available_options[1]="No" | |
available_options[2]="$two_word_element" | |
result_of_function="$(echo_passed_array "${available_options[@]}")" | |
echo "Result of function is: $result_of_function" | |
############### The output | |
List of options [0]: Yes | |
List of options [1]: No | |
List of options [2]: Maybe someday | |
Result of function is: No |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment