Bash xargs – How to Use Defined Functions

bashfunctionxargs

This is my code

#!/bin/bash

showword() {
  echo $1
}

echo This is a sample message | xargs -d' ' -t -n1 -P2 showword

So I have a function showword which echoes whatever string you pass as a parameter to the function.

Then I have xargs trying to call the function and pass one word at a time to the function, and run 2 copies of the function in parallel. The thing that is not working is xargs doesn't recognize the function. How can I achieve what I am trying to do, how can I make xargs work with the function showword?

Best Answer

Try exporting function, then calling it in a subshell:

showword() {
  echo $1
}

export -f showword
echo This is a sample message | xargs -d' ' -t -n1 -P2 bash -c 'showword "$@"' _
Related Question