You have a syntax error in your code. In the call to your loop
function, use "${arr[@]}"
to expand the arr
array to the list of each of its elements, individually quoted. This is what you do in the for
loop that you show, and this is also what you should do when calling the function:
loop echo "${arr[@]}"
Note also that your function needs to pick out the name of the command that you pass, and that it then needs to loop over its remaining arguments:
loop () {
local cmd=$1; shift
for arg do
"$cmd" "$arg"
done
}
Here, we assign the first argument to the variable cmd
(this is the command), then we shift
this argument off of the list of arguments. The list of arguments now contains only the strings that you want to loop over.
The loop then calls the command for each remaining argument in turn.
This replicates the purpose of the xargs
utility in a limited way, and the function can be re-implemented using this utility (unless you expect that one of the arguments will contain an embedded newline, in which case you will have to tweak the options to xargs
):
loop () {
local cmd=$1; shift
printf '%s\n' "$@" | xargs -L 1 "$cmd"
}
Since the xargs
utility expects data to be delivered over standard input, we arrange with this using printf
and print each argument given to loop
on a line of its own (while telling xargs
to call the given utility once for each newline-delimited argument using -L 1
).
This would allow us to use other features of some implementations of xargs
, like starting parallel processes using -P n
where n
is some number of processes to run in parallel.
Testing:
$ cat script.sh
loop () {
local cmd=$1; shift
printf '%s\n' "$@" | xargs -L 1 "$cmd"
}
arr1=(1 2 3)
arr2=("hello world" "home sweet home")
loop echo "${arr1[@]}"
loop echo "${arr2[@]}"
$ bash script.sh
1
2
3
hello world
home sweet home
iteration
orlooping
tag unix.stackexchange.com; should I move this to Stackoverflow? – Nishant Jun 22 '19 at 17:05loop echo $arr
is not how it actually works, or if it does work that way for you, you have a bug in your system. Similarlyloop echo "$arr[@]"
is also not how it works – jesse_b Jun 22 '19 at 17:18loop echo "$arr"
fromzsh
, corrected. – Nishant Jun 22 '19 at 17:19xargs
? – Kusalananda♦ Jun 22 '19 at 17:43