Simple Subcommands

  • bash
  • 4
  • 4
  • finished

Many of my personal Bash scripts follow a simple pattern: they have subcommands to do different things. Consider a “vpn” script which either connects or disconnects VPN. These are 2 subcommands: vpn connect and vpn disconnect. It’s useful to also add a third subcommand: vpn list-commands or vpn help to give a list of available subcommands without resorting to the source code. (sidenote: It’s also useful for completion scripts.)

Architecture of such scripts is simple: put each subcommand in a function which starts with some common prefix (for example “subc-“), convert the first argument of script to the name of the function and run it.

Here’s the template for copy-pasting:

#!/bin/bash

# Add new subcommands like this:
# subc-foo() {
#   :
# }

subc-help() {
    echo "Available commands:"
    grep '^subc-.*() {' "$0" | sort | sed -e 's/subc-/  - /' -e 's/().*//'
}


cmd="${1:-help}"; shift
"subc-${cmd}" "$@"