JSI Tip 5322. How do I use the SHIFT command to deal with a variable number of parameters?

When you open a CMD prompt and type SHIFT /?, you receive:

Changes the position of replaceable parameters in a batch file.

SHIFT \[/n\]

If Command Extensions are enabled the SHIFT command supports
the /n switch which tells the command to start shifting at the
nth argument, where n may be between zero and eight.  For example:

    SHIFT /2

would shift %3 to %2, %4 to %3, etc. and leave %0 and %1 unaffected.
You can use the SHIFT command to simplify the scripting of a batch file that can be passed a variable set of parameters.

If you needed to script a command that would append the contents of n files to to a target file, without erasing the existing contents of the target file, inserting a \[filename\] at the beginning of each source files content, the SHIFT commands provides an ideal solution. CopyA.bat could use the following syntax:

CopyA Target Source1 \[Source2\] \[Source3\] ... \[Sourcen\]


Target     is required and will be created if it does not exit.

Source1 is required and must exist.

Source2, Source3, etcetera are optional.

CopyA.bat could contain:

@echo off
if \{%2\}

\{\} goto syntax :loop if \{%2\}

\{\} endlocal&goto :EOF if not exist %2 goto syntax set header=\[%2\] set header=%header:"=% @echo %header%>>%1 copy %1+%2 %1 SHIFT /2 goto loop :syntax @echo Syntax CopyA Target Source1 \[Source2\] \[Source3\] ... \[Sourcen\] endlocal

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.