0

I would like to know if it is possible to make a more elegant solution for a batch file accepting arguments from another script. Looked at the solution here: Windows Bat file optional argument parsing, but can't make it work.

I have 19 arguments passed to the batch file. Arguments from the 7th are optional (come from checkboxes).

I have a working code with this structure:

REM arg7 parsing 
set LOGFILE=%7
if not "%LOGFILE%" == "LOGFILE" (
    set LOGFILE= 
) else ( 
shift /7 
)
REM arg8 parsing 
set ARG8=%7
if not "%ARG8%" == "ARG8" (
    set ARG8= 
) else ( 
   shift /7 
)
REM arg9 parsing 
set ARG9=%7
if not "%ARG9%" == "ARG9" (
  set ARG9= 
) else ( 
  shift /7 
)

And so on for each optional argument.

But now there are a lot of lines of similar code and it feels to me it could be optimized somehow. I'm not very familiar with batch scripting, so my tries of storing arguments in a list and trying to apply the above mentioned solution didn't work.

Community
  • 1
  • 1
AmeRyoki
  • 376
  • 1
  • 3
  • 14
  • Your question is about optimising lots of lines, if you're not providing the lots of lines, how are we supposed to optimize them. `IF "%7" EQU "LOGFILE" SHIFT /7` – Compo Sep 27 '16 at 08:09
  • it is exactly the same lines for 12 arguments with different argument name. But thanks for the comment, I will edit to make it more obvious. – AmeRyoki Sep 27 '16 at 08:18
  • please not I also provided a snippet which does the same thing as your example – Compo Sep 27 '16 at 08:19
  • Your example doesn't reset the value, if it is not equal "%7". I will have to write 12 lines of same code anyway. Not the perfect optimization imo. – AmeRyoki Sep 27 '16 at 08:28
  • my example didn't set a value, so didn't need to reset it! `IF "%7" EQU "LOGFILE" ((SET LOGFILE=%7) & SHIFT /7)` – Compo Sep 27 '16 at 08:34
  • You code is of course shorter, so it is an optimization in some way. Still it is not generalized, so not exactly what I'm looking for. – AmeRyoki Sep 27 '16 at 08:42

2 Answers2

1

Based on what you've posted, try this:

SET "_="
FOR %%I IN (
    LOGFILE ARG8 ARG9
    ) DO IF "%7" EQU "%%I" (SET "%%I=%7" & SET _=T)
IF DEFINED _ SHIFT /7

Just insert the other arguments on line three as is obvious.

Compo
  • 36,585
  • 5
  • 27
  • 39
1
@echo off
REM process optional parameters:
shift&shift&shift&shift&shift 
rem shift /5  :: couldn't get this to work...

set narg=6
:loop
shift
set /a narg+=1
if "%1" == "" goto :done
set arg%narg%=%1
goto :loop

:done
echo no more parameters
set arg
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • I had to combine your answer with upper one. I wouldn't want to touch not optional arguments, so Compo has better argument handling version. From yours I used the loop and got a working solution. Thanks! – AmeRyoki Sep 27 '16 at 10:18