Sub-commands with bash
Asked Answered
S

1

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

Shampoo answered 30/11, 2012 at 2:41 Comment(4)
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.Glyptograph
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.Shampoo
It's possible, but you would have to implement your own argument parser to handle sub-commands.Ohare
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.Shampoo
R
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.

Ramah answered 30/11, 2012 at 4:11 Comment(2)
You really should echo that rm command to be safe, or add a disclaimer.Ohare
@koola, yeah, you're right. Although I thought the help text was a disclaimer, along with the word "unsafe".Ramah

© 2022 - 2024 — McMap. All rights reserved.