ssb
ssb

Reputation: 209

pass parameters to a user defined function called by xargs

I have an array "foo". I want to pass the array to a self-defined function "bar" which is part of the xargs command. It takes me sometime to figure out how to invoke a user defined function in xargs. To achieve that, I export the function "bar" and use "bash -c" to execute it. However the $foo cannot be passed to bar(). $1 in bar() is empty.

Does anyone know how to solve this?

Thanks!!

foo="1 2 3 4 5 6 7 8 9"

bar(){
   echo $1
   echo "asdf"
   sleep 2
}

export -f bar

echo $foo | xargs -n 1 -P 3 bash -c bar

Upvotes: 2

Views: 973

Answers (1)

sarnold
sarnold

Reputation: 104050

I'd expect a new shell started via bash -c to not have access to your function. I'd expect it to only be available to subshells started with () or $() or ``.

If you want a newly started shell to have the function, perhaps store the function in a file and use --rcfile foo to load the function directly? Or, re-write it as a script file? (Since each execution of bash -c is already a new fork()/exec() pair, it might as well be to run your script directly.)

Upvotes: 1

Related Questions