Skip to content

Instantly share code, notes, and snippets.

@sdkks
Created February 1, 2023 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdkks/001420b2de29e4d6a593d2f30beffb93 to your computer and use it in GitHub Desktop.
Save sdkks/001420b2de29e4d6a593d2f30beffb93 to your computer and use it in GitHub Desktop.
Export variables and functions to use with xargs in parallel mode
#!/usr/bin/env bash
# Bash strict mode
# Error on undefined variable: -u
# Exit on ERR: -e
# Functions inherit ERR traps: -E
# Exit on pipe failures: -o pipefail
set -eEuo pipefail
# Directory of this script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# TRAP for exit cleanup
trap cleanup EXIT
cleanup(){
# Put your exit cleanup code here replacing no-op character
:
}
# TRAP for error reporting
trap 'err_report ${LINENO}' ERR
err_report() {
s=$?
local LINENO=$1
echo "$0: Error on line "$LINENO": $BASH_COMMAND"
exit $s
}
# Write your script below
myfunction(){
# Sleep if first parameter is "a"
# Needed to test parallel execution
[[ "$1" == "a" ]] && sleep 3
echo first parameter $1
echo all parameters $@
}
export -f myfunction
export MY_VARIABLE="foo"
export STDOUT_SAMPLE="a b c
1 2 3
x y z
foo bar baz
"
# "@@" is placeholder to be replaced
echo "$STDOUT_SAMPLE" | xargs -I@@ -P4 bash -c 'myfunction $@' -- @@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment