Multiple Parameters in Batch Files

You can pass as many parameters as you want to a batch job but the batch job can only access nine or ten of them at a time. The batch job uses %0 through %9 to contain the values that it has access to.

When the batch job first starts, %0 contains the string that was typed in to access the batch file and %1 through %9 contain the next nine fields that were typed. So if you are going to execute test.bat from your C: drive and you type c:\test.bat a b c d e f g h i j k l m then %0 will contain "c:\test.bat", %1 will contain "a", %2 "b",and so on %9 will contain "i". These fields can be referenced from within the batch file by placing the appropriate entry eg. %3 where we want the parameter to be substituted into the commands within the batch file.

So how do we access the rest of the parameters after the first nine? We use the shift command. Whenever your batch file executes "shift" all of the parameters will be moved down one. The contents of %1 will be moved to %0, %2 will be moved to %1, %9 to %8, and the next value entered will be moved to %9 thus becoming accessible. Of course once you have shifted the parameters there is no way to shift them back so you lose access to any that drop off from %0. This means that you will beed to be careful about when you shift the parameters to ensure that you will not lose access to ones that you still need.

So what can be done if some parameters are needed throughout the batch file? We do have one optional flag that can be specified on the shift command. We can lock so many of the parameters in place and only shift those above a specified number by specifying shift /n where n is the number below which the parameters are to be locked. So if we specify "shift /3" then %0, %1, and %2 will remain unchanged, the value currently in %3 will be lost and all of the subsequent parameters will be moved down one.

By carefully selecting the order in which parameters are to be specified and appropriate use of the shift command (with or without the switch) we can pass as many parameters into a batch file as we like (subject only to the maximum allowable command length).


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow