Last active
February 6, 2025 00:23
-
-
Save sgryjp/045989b0f6f0089a24f257d74b8a60bd to your computer and use it in GitHub Desktop.
Command line option (argument) parsing example for Windows batch file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:: Command line option (argument) parsing example | |
:: | |
:: Written by Suguru Yamamoto | |
:: <https://gist.github.com/sgryjp/045989b0f6f0089a24f257d74b8a60bd> | |
:: LICENSE: Public Domain | |
@echo off | |
setlocal enableextensions | |
:: Parse arguments | |
set _LEVEL=0 | |
set _QUIET=0 | |
set _FILES= | |
:ARGPARSE | |
set _=%~1 | |
if "%_:~,1%" == "/" ( | |
if /i "%~1" == "/Q" ( | |
set _QUIET=1 | |
) else if /i "%~1" == "/H" ( | |
set _HELP=1 | |
) else if /i "%~1" == "/L" ( | |
set _LEVEL=%~2 | |
shift | |
) else ( | |
echo Unknown option: %~1 | |
goto :EOF | |
) | |
) else ( | |
set _FILES=%_FILES% %1 | |
) | |
set _= | |
shift | |
if not "%~1" == "" goto ARGPARSE | |
if defined _HELP ( | |
echo Usage: %0 [/L LEVEL] [/Q] [/H] FILES | |
echo. | |
echo Parameters: | |
echo /L LEVEL Level of the operation. | |
echo /Q Do not prompt on operations. | |
echo /H Show this help and quit. | |
goto :EOF | |
) | |
:: Using command line arguments | |
echo QUIET: %_QUIET% | |
echo LEVEL: %_LEVEL% | |
echo FILES: %_FILES% | |
echo. | |
for %%I in (%_FILES%) do ( | |
echo [%%I] | |
if not %_QUIET% == 1 ( | |
echo dirpath: %%~dpI | |
echo fullpath: %%~fI | |
echo. | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment