Search code examples
bashsubcommand

Sub-commands with bash


Is it possible to implement sub-commands for bash scripts. I have something like this in mind:

http://docs.python.org/dev/library/argparse.html#sub-commands


Solution

  • Here's a simple unsafe technique:

    #!/bin/bash
    
    clean() {
      echo rm -fR .
      echo Thanks to koola, I let you off this time,
      echo but you really shouldn\'t run random code you download from the net.
    }
    
    help() {
      echo Whatever you do, don\'t use clean
    }
    
    args() {
      printf "%s" options:
      while getopts a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z: OPTION "$@"; do
        printf " -%s '%s'" $OPTION $OPTARG
      done
      shift $((OPTIND - 1))
      printf "arg: '%s'" "$@"
      echo
    }
    
    "$@"
    

    That's all very cool, but it doesn't limit what a subcommand could be. So you might want to replace the last line with:

    if [[ $1 =~ ^(clean|help|args)$ ]]; then
      "$@"
    else
      echo "Invalid subcommand $1" >&2
      exit 1
    fi
    

    Some systems let you put "global" options before the subcommand. You can put a getopts loop before the subcommand execution if you want to. Remember to shift before you fall into the subcommand execution; also, reset OPTIND to 1 so that the subcommands getopts doesn't get confused.