Parsing of the command line switches into variables

Aug 23, 2010
688
9
My use case was that I needed to parse a few command line switches and set some variables from them.
The hard part is that they could include "=" as name-value separators, or could not.
There's my small hack on the subject:
Code:
:: PARAMETRIZE [name param]
ALIAS PARAMETRIZE=SET __name=^%1 ^%+ SET __value=^%@REREPLACE[^^--.*?=,,^%2] ^%+ IFF "%%[__value]" != "%%2" THEN ^%+ SET ^%[__name]=^%[__value] ^%+ UNSET __name ^%+ ENDIFF ^%+ UNSET __value

SET _enc=UTF-8
SET _session=local

DO param IN /Q %$ ""
  SET param=%@UNQUOTES[%[param]]
  IFF "%[__name]" != "" THEN
    SET %[__name]=%[param]
    UNSET __name
    SHIFT
  ELSE
    SWITCH %@REREPLACE[=.*$,,%[param]]
      CASE --encoding
        PARAMETRIZE _enc %[param]
        SHIFT
      CASE --name
        PARAMETRIZE _session %[param]
        SHIFT
      CASE --root
        PARAMETRIZE _root %[param]
        SHIFT
      DEFAULT
        LEAVE
    ENDSWITCH
  ENDIFF
ENDDO

IFF "%[_root]" != "" THEN
  SET _root=-t %[_root]
ENDIFF

It has a few flaws I did not care to solve (parameter unquoting should be done before passing parameters to the alias, for one), but otherwise works like a charm.
Optionally, if you want to handle "--", include
Code:
        IFF "%[param]" == "--" THEN
          SHIFT
        ENDIFF
before `LEAVE` in the DEFAULT block.