Article Image
read

Bash Argument Parsing

After working with great libraries like NodeJS's minimist, I sometimes find it hard to go back to other languages where things take a very "reimplement it every time you need it" or a "this works, but not in case XYZ" approach.

I was faced with this problem yet again when developing some wrapper scripts for docker swarm: I can do simple argument-matching in bash, but that's order-dependent, and only supports opt-in flags.

Introducing bash-minimist

So, under the inspiration of NodeJS minimist, I developed bash-minimist: A simple and opinionated script that will export flags, values, and positional arguments through variables, and let your script handle the rest. It's not documentation (Doesn't implement --help for you), nor is it error-checking (it will happily let most values through).

Example

#!/bin/bash

# This is all you have to do to use it
# Once used, all flags will be removed from $@ (Not in $1 $2, etc..)
# And all arguments and values will be declared under ARG_ (by default)
source minimist.sh

if [[ $ARG_n == 'y' ]]; then
    echo "-y" was set
fi

if [[ $ARG_k == 'y' ]]; then
    echo "-k was set"
fi

echo "Positionals $1 $2 $3"
echo "Flags: ABC=$ARG_ABC"

Alright, the above is a nieve example, but now you can do this:

$ ./example -y -k --abc=123 pos1 pos2 pos3
# OR THIS
$ ./example pos1 pos2 -yk --abc=123 pos3
# OR THIS
$ ./example -yk --abc=123 -- pos1 pos2 --pos3

Help-text

My pattern providing help looks like this:

#!/bin/bash

function abortHelp() {
  echo "Usage:"
  echo "  $0 <positional1> [flags]"
  echo "  -h --help   Show this help"
  echo "  -t --tun    Create tunnel"
  exit 1
}

source minimist.sh

if [[ $ARG_h == 'y' || $ARG_HELP == 'y' ]]; then
    abortHelp
fi

if [[ -z $1 ]]; then
  echo "Required pos arg 1"
  abortHelp
fi

if [[ $ARG_t == 'y' || $ARG_TUN == 'y' ]]; then
  echo "You want a tunnel"
fi

echo "Tunneling to $1"

Getting started

Simply head over to bash-minimist, download minimist.sh, and source it in your script today!

wget -O minimist.sh https://raw.githubusercontent.com/zix99/bash-minimist/master/minimist.sh
Blog Logo

Christopher LaPointe


Published

Image

Chris LaPointe

Another site of Code

Back to Overview