这是我正在处理的代码:
function execute {
task="$1"
servername="$2"
"$task" "${servername[@]}"
}
function someOtherThing {
val=$1
echo "$val"
}
function makeNecessaryDirectory {
arr=("$@")
echo "${arr[@]}"
}
dem=(1 2 3 4 5)
execute someOtherThing 1
execute makeNecessaryDirectory "${dem[@]}"
输出:
1
1
预期产量:
1
1 2 3 4 5
如何实现呢?我发现逻辑上没有错误。
Side question
:
始终将第2个参数作为内部数组接收是否安全,execute
以便它可以处理两个相关函数,还是我应该在内部进行显式检查execute
?
如我的评论中所述
您要将数组作为单个argsexecute
传递给,然后仅将第一个传递给makeNecessaryDirectory
,因此$@
传递的唯一参数也就是1。
我将以这种方式进行操作,在已更改的部分中添加了注释。这只是微小的更改,但希望可以为您工作。
#!/bin/bash
function execute {
task="$1"
servername="$2"
"$task" "$servername"
#No longer pass array here just pass servername as the name of array
}
function someOtherThing {
val=$1
echo "$val"
}
function makeNecessaryDirectory {
local arr=("${!1}")
#Indirect reference to the first arg passed to function which is now the
#name of the array
for i in "${arr[@]}";
do
echo "$i"
done
}
dem=(1 2 3 4 5)
execute someOtherThing 1
execute makeNecessaryDirectory 'dem[@]' #Pass the array name instead of it's contents
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句