#!/usr/bin/env bash
#
# forarg - run a command within several args
# usage: forargs [-c echo]

PARALLEL=0
cmd="echo -e"

POSITIONAL=()
while [ "$#" -gt 0 ]; do
  key="$1"
  case ${key} in
    -p | --parallel)
      PARALLEL=1
      shift
      ;;
    -c | --cmd | --command)
      cmd="$2"
      shift 2
      ;;
    *)
      POSITIONAL+=("$1")
      shift
      ;;
  esac
done
# restore positional parameters
set -- "${POSITIONAL[@]}"

if [ "${PARALLEL}" = 0 ]; then
  for ARG in "$@"; do
    ${cmd} "${ARG}"
  done
elif command -v parallel; then
  export cmd
  parallel "${cmd}" ::: "$@"
else
  for ARG in "$@"; do
    "${cmd}" "${ARG}" >out.log 2>&1 &
  done
  wait
fi
