LoginSignup
1
2

More than 5 years have passed since last update.

# バッチファイルでコマンドラインオプション処理を書いてみた

Last updated at Posted at 2018-02-20

Windows 環境でも bash や powershell やらが使える時代だし batch 卒業記念としてコマンドラインオプション周りの処理を少し真面目に書いてみた。 (バッチ関係のタグ記事が分散してて微妙

@echo off
goto :Init

:Version
echo %PROGRAM% Version 0.0.0
exit /b 1

:Help
echo.Usage: %PROGRAM% [Options]
echo.Options
echo.  --HELP,-H,^/? ... this help
echo.  --VERSION    ... out version
echo.  --VERBOSE    ... verbosely
echo.  --DRYRUN     ... dry run
echo.  --DIR DIR    ... excute directory default .
exit /b 1

:Init
setlocal
set "PROGRAM=%~f0"
set "OPTIONS=%*"
set "VERBOSE="
set "DRYRUN="
set "SEPARATOR="
set "THRUOPTIONS="
set "ACTION="
set "DIR=."

:GetOpt
set OPTION=%1
if not defined OPTION goto :GetOptEnd
if defined VERBOSE echo [VERBOSE] GetOpt %1 %2
if %OPTION:~0,1%%OPTION:~-1,1% == "" set OPTION=%OPTION:~1,-1%
call :GetValue %2
if "%OPTION%" == "--VERBOSE" (
    if defined VERBOSE ( shift && goto :GetOpt )
    set "VERBOSE=1"
    echo [VERBOSE] PROGRAM %PROGRAM%
    echo [VERBOSE] OPTIONS %OPTIONS%
    goto :GetOpt
)
if "%OPTION%" == "/?" set "OPTION=--HELP"
if "%OPTION%" == "-H" set "OPTION=--HELP"
if "%OPTION%" == "--HELP" ( set "ACTION=%OPTION%" && shift && goto :GetOpt )
if "%OPTION%" == "--VERSION" ( set "ACTION=%OPTION%" && shift && goto :GetOpt )
if "%OPTION%" == "--DRYRUN" ( set "DRYRUN=1" && shift && goto :GetOpt )
if "%OPTION%" == "--DIR" (
    if not defined VALUE goto :GetOptError 
    set DIR=%VALUE%
    shift
    shift
    goto :GetOpt
)
set THRUOPTIONS=%THRUOPTIONS%%SEPARATOR%%1
set."SEPARATOR= "
shift
goto :GetOpt

:GetValue
set VALUE=%1
if not defined VALUE exit /b
if %VALUE:~0,1%%VALUE:~-1,1% == "" set VALUE=%VALUE:~1,-1%
exit /b

:GetOptError
echo [ERROR] Illegal Option '%OPTION%'
exit /b 1

:GetOptEnd
if defined VERBOSE echo [VERBOSE] THRUOPTION %THRUOPTIONS% 
if defined ACTION if defined VERBOSE echo [VERBOSE] ACTION %ACTION%
if "%ACTION%"=="--VERSION" goto :Version
if "%ACTION%"=="--HELP" goto :Help
call <nul :Main %THRUOPTIONS%
exit /b

:Main
if defined VERBOSE echo ^
[VERBOSE] change directory "%DIR%"
pushd "%DIR%"

if defined DRYRUN echo ^
[MESSAGE] DRYRUN
if not defined DRYRUN echo ^
[MESSAGE] RUN

popd
exit /b
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2