解析Windows命令行开关

时间:2014-03-29 19:09:45

标签: batch-file command-line switch-statement

我一直在寻找一种解析和解释Windows命令开关的简便方法。我已经知道如何捕获%*,%1等,但我似乎无法看到有关如何解析复合标记的任何资源,例如在Git中:-am

我一直在努力尝试:

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

但无济于事。我认为命令行有更简单的语法来处理它们。我想处理-a -m以及-am等方案。

我也很好奇你如何编写批处理文件,以便参数的顺序不受限制。

2 个答案:

答案 0 :(得分:2)

这是一种简单的方法:

@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

编辑:以下修改还允许组合多个开关,例如-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

答案 1 :(得分:0)

复杂的选项,标记,未知的错误和顺序并不重要:

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

没有嵌套for循环,使用shift和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%