这是一个示例,说明如何使用递归来一次设置一个参数列表。该技术有时很有用。
使用进程替换将文本转换为管道可能不是当前问题的最佳解决方案,但它确实具有重用现有工具的优点。
我试图使代码合理通用,但可能需要进行更多调整。
nameref 需要 Bash 4.3(尽管如果您尚未达到该版本,则可以使用固定的数组名称来执行此操作)。Namerefs 需要谨慎,因为它们不卫生;可以按名称捕获局部变量。因此使用以下划线开头的变量名。
# A wrapper which sets up for the recursive call
from_array() {
local -n _array=$1
local -a _cmd=("${@:2}")
local -i _count=${#_array[@]}
from_array_helper
}
# A recursive function to create the process substitutions.
# Each invocation adds one process substitution to the argument
# list, working from the end.
from_array_helper() {
if (($_count)); then
((--_count))
from_array_helper <(printf %s "${_array[_count]}") "$@"
else
"${_cmd[@]}" "$@"
fi
}
例子
$ a=($'first\nsecond\n' $'x\ny\n' $'27\n35\n')
$ from_array a paste -d :
first:x:27
second:y:35