13

I'm writing a Batch script that will run on a directory. I want to be able to add a flag (such as -r or /r or something like that) that will make the script run the folder tree instead of the single directory. Is it possible to add flag options using batch?

Thanks

ZackG
  • 177
  • 3
  • 3
  • 9
  • [command line parameters](http://www.robvanderwoude.com/parameters.php). Did you bother [Googling this](http://goo.gl/e6Kc9)? – rojo Feb 28 '13 at 19:02
  • 1
    possible duplicate of [Windows Bat file optional argument parsing](http://stackoverflow.com/questions/3973824/windows-bat-file-optional-argument-parsing) – Andriy M Feb 28 '13 at 22:37

1 Answers1

21

Certainly it's possible. Command line parameters are passed in to your batch file as %1, %2, etc. (%0 is the name of the batch file.)

IF "%1"=="/r" ECHO You passed the /r flag.

Use SHIFT to drop the first argument and move all the others over by one. You can use that to get a bit fancier if you want to allow that /r to be anywhere in the command line. For example:

:processargs
SET ARG=%1
IF DEFINED ARG (
    IF "%ARG%"=="/r" ECHO You passed the /r flag.
    SHIFT
    GOTO processargs
)

Or use %* (which expands to the entire argument list) in a FOR loop like this:

FOR %%A IN (%*) DO (
    IF "%%A"=="/r" ECHO You passed the /r flag.
)
Nate Hekman
  • 6,507
  • 27
  • 30
  • 2
    You can also process arguments as `%*` with a `for` loop. [Example](http://stackoverflow.com/a/15002975/1683264) – rojo Feb 28 '13 at 19:44
  • Why the `SET ARG=%1`, `IF DEFINED ARG` rather than `IF NOT '%1'==''`? – Sinjai Jan 22 '18 at 09:52
  • @Sinjai: personal preference. :-) I always like to name variables so the intent is clear, and similarly "if defined" communicates the intent better than a comparison. – Nate Hekman Jan 23 '18 at 15:31
  • @Nate: I figured, just making sure I didn't miss something. It's probably not a bad rule of thumb anyway, as often I find myself consistently interested in, say, `%~1` and named variables allow for substrings, etc. Though these are all concepts I was not familiar with when I made that comment! – Sinjai Jan 23 '18 at 21:27