TIL: Call bash function via xargs

:til: :cli: :bash:

To run cli tools there is xargs. But what if I want to run certain part of bash script (a function) in parallel? One option is to extract function to a separate file and feed it into xargs. Another way - make xargs to execute the function:

#!/bin/bash

p() {
    echo "> $1"
}

main() {
    export -f p
    seq 10 | xargs -n 1 -I {} bash -c  "p {}"
}

main "@$"

Necesary line here is to export the function via export -f <function_name>. Once function is exported to the scope, xargs can access it and execute call to the function. The p {} part means value from seq command is provided to function p. E.g. p 10.