How to use defined function with xargs

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="547014">[email protected]</a>"' _

Method 2

Just adding an alternative solution using parallel which I have started using in place of xargs. The task is much easier with parallel

#!/bin/bash

showword() {
  echo $1
}
export -f showword

parallel -j2 showword {} ::: This is a sample message
  • -j2 makes sure 2 copies of the function is run in parallel
  • ::: anything after this is passed as separate arguments to parallel, separation is whitespace
  • {} is replaced by the argument passed into parallel and fed into the showword function

If you are using zsh shell this solution will not work since zsh does not have any feature to export functions. You will need something like this:

#!/usr/bin/zsh

showword() {
  echo $1
}

# add the following to your .zshrc if you want env_parallel in your shell permanently
source /usr/bin/env_parallel.zsh

env_parallel -j2 --env showword showword {} ::: This is a sample message


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x