-2

I am creating a batch program, and you need to pass arguments to it. Though with my current code you have to pass the arguments in a certain way. The way I could fix this is by getting a line of text next to the argument. This is what I want :

batch.bat -arg2 arg -arg1 arg
                 ^         ^
                 |         |
              Need This Need This
KyLeCoOl
  • 37
  • 4
  • 1
    Well `batch.bat` will see your required arguments as `%2`, _(string following `-arg2`)_, and `%4`, _(string following `-arg1`)_, is that what you wanted to know? or is there something else you wanted? Also you may be interested in the `Shift` command, please open a Command Prompt window and enter `shift /?` to read its usage information. – Compo Aug 24 '19 at 14:29
  • OK, here's my problem: My batch file has 2 different arguments, let's say -1 and -2. Those 2 arguments are required, but the user could get the order messed up, Which will make my batch file behave in a weird way. For example, batch.bat -1 arg1 -2 arg2. They are in the correct order. But batch.bat -2 arg2 -1 arg1? It will make my batch file behave in a weird way. Hope this helps. – KyLeCoOl Aug 24 '19 at 14:36

1 Answers1

0

here is a skeleton to use. If you don't trust your users, you will have to add some precautions (like checking if arguments come in pairs or if the first argument of a pair starts with a - and the second doesn't)

@Echo Off
setlocal
:loop
if "%~2" == "" goto :continue
set "%~1=%~2"
shift
shift
goto :loop
:continue
REM check the parameters:
set - 2>nul

Try with

batch.bat -arg2 world -arg1 hello

Alternative syntax (without changing the code):

batch.bat -arg2=world -arg1=hello

(maybe better understandable by users)

Stephan
  • 53,940
  • 10
  • 58
  • 91