这是一个示例,其中我将 2 个 bash 数组接收到一个函数中,以及它们之后的附加参数。对于任意数量的 bash 数组和任意数量的附加参数,只要每个 bash 数组的长度恰好位于该数组的元素之前,这种模式就可以无限期地继续下去,以适应任何输入参数顺序。
的函数定义print_two_arrays_plus_extra_args
:
# Print all elements of a bash array.
# General form:
# print_one_array array1
# Example usage:
# print_one_array "${array1[@]}"
print_one_array() {
for element in "$@"; do
printf " %s\n" "$element"
done
}
# Print all elements of two bash arrays, plus two extra args at the end.
# General form (notice length MUST come before the array in order
# to be able to parse the args!):
# print_two_arrays_plus_extra_args array1_len array1 array2_len array2 \
# extra_arg1 extra_arg2
# Example usage:
# print_two_arrays_plus_extra_args "${#array1[@]}" "${array1[@]}" \
# "${#array2[@]}" "${array2[@]}" "hello" "world"
print_two_arrays_plus_extra_args() {
i=1
# Read array1_len into a variable
array1_len="${@:$i:1}"
((i++))
# Read array1 into a new array
array1=("${@:$i:$array1_len}")
((i += $array1_len))
# Read array2_len into a variable
array2_len="${@:$i:1}"
((i++))
# Read array2 into a new array
array2=("${@:$i:$array2_len}")
((i += $array2_len))
# You can now read the extra arguments all at once and gather them into a
# new array like this:
extra_args_array=("${@:$i}")
# OR you can read the extra arguments individually into their own variables
# one-by-one like this
extra_arg1="${@:$i:1}"
((i++))
extra_arg2="${@:$i:1}"
((i++))
# Print the output
echo "array1:"
print_one_array "${array1[@]}"
echo "array2:"
print_one_array "${array2[@]}"
echo "extra_arg1 = $extra_arg1"
echo "extra_arg2 = $extra_arg2"
echo "extra_args_array:"
print_one_array "${extra_args_array[@]}"
}
示例用法:
array1=()
array1+=("one")
array1+=("two")
array1+=("three")
array2=("four" "five" "six" "seven" "eight")
echo "Printing array1 and array2 plus some extra args"
# Note that `"${#array1[@]}"` is the array length (number of elements
# in the array), and `"${array1[@]}"` is the array (all of the elements
# in the array)
print_two_arrays_plus_extra_args "${#array1[@]}" "${array1[@]}" \
"${#array2[@]}" "${array2[@]}" "hello" "world"
示例输出:
Printing array1 and array2 plus some extra args
array1:
one
two
three
array2:
four
five
six
seven
eight
extra_arg1 = hello
extra_arg2 = world
extra_args_array:
hello
world
有关其工作原理的更多示例和详细说明,请在此处查看我对此主题的更长回答:Passing arrays as parameters in bash