5

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

LavaScornedOven
  • 737
  • 1
  • 11
  • 23
  • not sure what you are getting at. you could add a program call "svn" which would then parse all the svn commands. in a way that's all bash does is invoke sub commands. – kdubs Nov 30 '12 at 02:48
  • argparse does flag parsing for programs that support command-line interface, e.g. `git clean -df` would be parsed as `clean` sub-command, and `-df` are `clean`-specific flags. – LavaScornedOven Nov 30 '12 at 02:57
  • It's possible, but you would have to implement your own argument parser to handle sub-commands. – koola Nov 30 '12 at 03:11
  • 1
    Do you maybe know of some tutorial, post, or resource of any kind on that topic? I couldn't find anything useful as a starting point. – LavaScornedOven Nov 30 '12 at 03:25

1 Answers1

8

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.

rici
  • 234,347
  • 28
  • 237
  • 341
  • 2
    You really should echo that rm command to be safe, or add a disclaimer. – koola Nov 30 '12 at 07:56
  • 1
    @koola, yeah, you're right. Although I thought the help text was a disclaimer, along with the word "unsafe". – rici Nov 30 '12 at 23:07