1

I'm trying to handle my script's command line arguments more elegantly. I really like the way getopt handles arguments in C, but at this point in my script it's not worth rewriting it in a new language. I came across this thread: https://stackoverflow.com/a/3661082, that included this method that I really liked:

:GETOPTS
if /I "%1" == "-h" goto Help
if /I "%1" == "-b" set BASE=%2 & shift
if /I "%1" == "-s" set SQL=%2 & shift
shift
if not "%1" == "" goto GETOPTS

Credit to @tivnet and @Kris

I also found this answer in another thread that also used mandatory parameters, but in their scenario they had the mandatory arguments first, whereas I would like to use them at the end.

@ECHO OFF

SET man1=%1
SET man2=%2
SHIFT & SHIFT

:loop
IF NOT "%1"=="" (
    IF "%1"=="-username" (
    SET user=%2
    SHIFT
)
IF "%1"=="-otheroption" (
    SET other=%2
    SHIFT
)
SHIFT
GOTO :loop
)

Credit to @ewall


In my implementation of argument handling, I have an issue of the two mandatory arguments being empty after the optional, named arguments. An example of how the arguments should be entered:

script.cmd [-F file-type] [-D delete-old] SOURCE DEST

@ECHO OFF

:GETOPTS
if /I "%1"=="-h" GOTO HELP
if /I "%1"=="-F" set fileType=%2 & SHIFT
if /I "%1"=="-D" set deleteOld=%2 & SHIFT
SHIFT
if not "%1"=="" GOTO GETOPTS
SHIFT & SHIFT

set source=%1
set dest=%2

When I try to echo %source% and %dest%, I get empty responses. The other variables I set work as expected. Where am I going wrong?


I just found this solution on SuperUser, so I'm trying to use some of the methodologies that they use to detect if an argument is an option or a parameter. If someone can combine them better than I, please do.

  • it is really simple. Decide on which switches can be used together, then which not, then place each of them in the %n position and test whether they are a switch or a parameter. – Gerhard Jan 25 '18 at 14:28

1 Answers1

0

I was able to get something working after a lot of trial and error. Some of the lessons I learned doing this was that flags without any arguments do not need their own SHIFT.

@ECHO OFF

:GETOPT
if /I "%1"=="-h" goto HELP
if /I "%1"=="--help" goto HELP
if /I "%1"=="-v" goto VERSION
if /I "%1"=="--version" goto VERSION
if /I "%1"=="-F" set fileType=%2 & SHIFT
if /I "%1"=="-D" set deleteOld=1
SHIFT
set source=%1
set dest=%2
if not "%3"=="" goto GETOPT
goto EOF