Thursday, April 7, 2022

[SOLVED] common bash function to check arguments and if "--help" was passed, then call a help function

Issue

I have the following condition in a few bash functions to print their help message, but I realized that this is such an annoying repetition and wonder if there's a way around it so that the condition and call happen in a single wrapper function. So instead of this:

fn1() {
  arg=$@
  [ ! -z $arg ] || [ $arg = "--help" ] && helpit "fn1 help msg." && return

  # fn body here
}
fn2() {
  arg=$@
  [ ! -z $arg ] || [ $arg = "--help" ] && helpit "fn2 help msg." && return

  # fn body here
}

We have this:

try_help() {
  # FYI $@ is the help msg and not the params of its caller
  arg=$@
  [ ! -z $arg ] || [ $arg = "--help" ] && helpit "Delete a remote branch by name." && return 1
  return 0
}
fn1() {
  try_help "fn1 help msg." || return

  # fn body here
}
fn2() {
  try_help "fn2 help msg." || return

  # fn body here
}

Is this possible to do?


Solution

Trivially done.

helpit() { echo "$*" >&2; }
try_help() {
  local help_msg arg
  help_msg=$1; shift
  if (( $# == 0 )); then
    echo "No arguments found. Printing help:" >&2
    helpit "$help_msg"
    return 1
  fi
  for arg in "$@"; do
    case $arg in
      --)     return 0;;
      --help) helpit "$help_msg"; return 1;;
    esac
  done
  return 0
}

fn1() {
  try_help "fn1 help msg" "$@" || return
  # fn body here
}
fn2() {
  try_help "fn2 help msg" "$@" || return
  # fn body here
}


Answered By - Charles Duffy
Answer Checked By - Cary Denson (WPSolving Admin)