#!/bin/sh
#
# pid2name - print out corresponding process names from given pids
# silently ignores pids it cant find

getname() {
  case "$(uname)" in
    Darwin)
      ps -p "$1" -o command= 2>/dev/null \
        | while read -r name _; do
          # print only the process name, not full path
          printf '%s\n' "${name##*/}"
        done
      ;;
    *)
      name="$(cat /proc/"$1"/comm)"
      echo "${name}"
      ;;
  esac
}

if [ -n "$1" ]; then
  # shellcheck disable=SC2249
  case "$1" in
    -h | --help)
      {
        sed -n '2,/^#$/ s/^# //p' <"$0"
        exit 1
      }
      ;;
  esac
  # assume were given pids as argument then
  for pid in "$@"; do
    getname "${pid}"
  done
else
  # we are given piped input
  while read -r pid; do
    getname "${pid}"
  done
fi
