Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Bash can also employ a kind of function pointer, which can greatly simplify command-line argument parsing. Consider the following simplified example:

    ARG_ARCH="amd64"

    ARGUMENTS+=(
      "ARG_ARCH,a,arch,Target operating system architecture (${ARG_ARCH})"
      "log=utile_log,V,verbose,Log messages while processing"
    )

    utile_log() { echo "$1" }

    noop()      { return 1 }

    log=noop
By creating a comma-delimited list of command-line arguments, the parsing logic and control flow can be influenced from a single location in the code base. The trick is to eval-uate "log=utile_log" when the "-V" command-line argument is provided (or assign ARG_ARCH to the user-supplied value after "-a"). Using the $log variable invokes the function, such as in:

    preprocess() {
      $log "Preprocess"
    }
If "-V" isn't supplied, then every invocation of $log simply returns without printing a message. The upshot is a reduction in conditional statements. Function pointers FTW. I wrote about this technique in my Typesetting Markdown series:

https://dave.autonoma.ca/blog/2019/05/22/typesetting-markdow...

Here's a rudimentary implementation and example usage to wet your whistle:

https://github.com/DaveJarvis/keenwrite/blob/master/scripts/...

https://github.com/DaveJarvis/keenwrite/blob/master/installe...



It also works with dynamic names, if you need a slightly different entry point and don't want to risk conflicting with other function names:

  run_foo() { echo foo; }
  run_bar() { echo bar; }
  name=foo
  run_$name


This kind of thing terrifies me when I see it in in code -- particularly when it's something like `$VAR -flags` -- because my first thought is always

> "what if that variable isn't set to whatever the developer is expecting it to be set? What random command will then be executed?"

As an author of an alternative shell myself, I purposely removed this ability for that reason.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: