user776686
user776686

Reputation: 8655

Parsing Windows command line switches

I have been searching for an easy way to parse and interpret Windows command switches. I already know how to capture %*, %1, etc. but I can't seem to see any resource on how to parse compound flags such as in Git: -am.

I have been trying with something like:

echo(%1|findstr /r /c:"^-.*" >nul && (
  echo FOUND
  rem any commands can go here
) || (
  echo NOT FOUND
  rem any commands can go here
)

but to no avail. I thought the command line had easier syntax to deal with them. I want to handle scenarios like -a -m as well as -am.

I would also be curious how you code the batch file so that the sequence of the arguments is unrestricted.

Upvotes: 1

Views: 400

Answers (2)

B.McKee
B.McKee

Reputation: 430

Complex options, flags, error on unknown, and order doesn't matter:

C:\DEV>usage /?
Usage: usage.cmd [/A word] [/B word] /c /d
Error: Unknown Option: /?

C:\DEV
>usage /b /B word /A "no way"
A="no way" B=word a= b=true

No nested for loops, using shift and goto.

@echo off

set FlagA=
set FlagB=

:Options
if "%1"=="/A" (
  set OptionA=%2
  shift
  shift
  goto Options
)
if "%1"=="/B" (
  set OptionB=%2
  shift
  shift
  goto Options
)
if "%1"=="/a" (
  set FlagA=true
  shift
  goto Options
)
if "%1"=="/b" (
  set FlagB=true
  shift
  goto Options
)
if "%1" NEQ "" (
  echo Usage: %~n0%~x0 [/A word] [/B word] /c /d
  echo Error: Unknown Option: %1
  goto :EOF
)

echo A=%OptionA% B=%OptionB% a=%FlagA% b=%FlagB%

Upvotes: 1

Aacini
Aacini

Reputation: 67216

This is a simple way to do that:

@echo off
setlocal EnableDelayedExpansion

rem Process parameters and set given switches
for %%a in (%*) do (
  set opt=%%a
  if "!opt:~0,1!" equ "-" set switch[%%a]=true
)

rem Use the given switches
if defined switch[-a] echo Switch -a given
if defined switch[-m] echo Switch -m given

EDIT: The modification below also allows to combine several switches, like in -am:

@echo off
setlocal EnableDelayedExpansion

rem Define possible switches
set switches=a m

rem Process parameters and set given switches
for %%a in (%*) do (
  set opt=%%a
  if "!opt:~0,1!" equ "-" (
      for %%b in (%switches%) do (
         if "!opt:%%b=!" neq "!opt!" set switch[-%%b]=true
      )
   )
)

rem Use the given switches
if defined switch[-a] echo Switch -a given
if defined switch[-m] echo Switch -m given

Upvotes: 2

Related Questions