Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created May 8, 2023 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/a6c3fc433e7f98ef74f6cb45f4f2a952 to your computer and use it in GitHub Desktop.
Save guitarrapc/a6c3fc433e7f98ef74f6cb45f4f2a952 to your computer and use it in GitHub Desktop.
Using parameters in batch files at Windows command line.
@echo off
:: parse.bat --foo --bar
:: parse.bat --foo --bar --param 1
:: parse.bat --foo --bar --param2 5
:: parse.bat --foo --bar --param2 5 --param 100
:: parse.bat --foo --bar --param 1 --param2 5
setlocal
:parse
if "%~1"=="" GOTO endparse
if "%~1"=="--foo" (set _FOO=true)
if "%~1"=="--bar" (set _BAR=true)
if "%~1"=="--param" (set _PARAM=%~2)
if "%~1"=="--param2" (set _PARAM2=%~2)
shift
GOTO parse
:endparse
:: debug
if "%_FOO%"=="true" echo --foo detected
if "%_BAR%"=="true" echo --bar detected
if not "%_PARAM%"=="" echo --param %_PARAM%
if not "%_PARAM2%"=="" echo --param2 %_PARAM2%
endlocal
@guitarrapc
Copy link
Author

Equivalent to following bash script.

#!/bin/bash
set -euo pipefail

while [ $# -gt 0 ]; do
    case $1 in
        --foo) _FOO=true; shift 1; ;;
        --bar) _BAR=true; shift 1; ;;
        --param) _PARAM=$2; shift 2; ;;
        --param2) _PARAM2=$2; shift 2; ;;
        *) shift ;;
    esac
done

if [[ "${_FOO:=""}" == "true" ]]; then echo "--foo detected"; fi
if [[ "${_BAR=""}" == "true" ]]; then echo "--bar detected"; fi
if [[ "${_PARAM:=""}" != "" ]]; then echo "--param ${_PARAM}"; fi
if [[ "${_PARAM2:=""}" != "" ]]; then echo "--param2 ${_PARAM2}"; fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment