by Barry Dysert
(last updated August 18, 2014)
You may find the SHIFT statement useful in some of your batch files. What SHIFT does is shift the parameters passed to the batch file from right to left. This gives you one way, for example, to have your batch file accept a variable number of parameters.
Internally, the command interpreter numbers elements of the command line. For instance, consider the following command that executes a batch file name DOIT.BAT:
doit first second third fourth fifth
In this instance, the command provides five parameters to the DOIT.BAT file. The command interpreter, internally, numbers these parameters %1 through %5. In reality, though, there is a "parameter" numbered %0: the batch file name itself. Create your own DOIT.BAT file that contains the following:
@ECHO OFF CLS :TOP IF [%0]== GOTO :EOF ECHO %0 %1 %2 %3 %4 %5 SHIFT GOTO TOP
All the batch file does is to echo, to the screen, the elements of the command line and then shifts (through the SHIFT command) all the elements to the left. After the shift, element %0 is discarded, element %1 becomes %0, element %2 becomes %1, and so on. When you run the batch file, you should see the following output:
doit first second third fourth fifth first second third fourth fifth second third fourth fifth third fourth fifth fourth fifth fifth
When you use SHIFT in your batch file, you can invoke the file with a variable number of parameters and then shift through them to do your processing.
This tip (13198) applies to Windows 7 and 8.
This tip is part of a series that talks about Windows batch files. It introduces a few more commands and special characters ...Discover More
Once you become comfortable with batch files, chances are that you'll want to use them to perform various system maintenance ...Discover More
This tip is part of a series that talks about Windows batch files. It introduces a few more commands you can use in your ...Discover More
FREE SERVICE: Get tips like this every week in WindowsTips, a free productivity newsletter. Enter your address and click "Subscribe."