Thursday, November 6, 2025

Positional Arguments in Windows Batch Scripting

We can run a batch file either of the following ways:
  1. By mouse click of the batch file
  2. By running the batch file on CMD prompt.
In the second case, we can easily pass arguments to the command.

Look at the following Batch Script file args.bat:

@echo off
echo First argument is %1
echo 2nd argument is %2
echo 3rd argument is %3
pause

We can pass three arguments when running the batch script file. Look at the image below:

Now run the following command in CMD window: SHIFT/? We get the following help:
C:\Users\ajeet>shift/?
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.

The SHIFT command is used shift the arguments. The SHIFT command moves the arguments down, essentially discarding the first one (%1) and moving the second one (%2) into the %1 position, the third (%3) into %2, and so on. This is extremely useful for looping through an unknown number of arguments. Look at the following example file args2.bat in this regard:

@echo off
echo First argument is %1
shift
echo 2nd argument is %1
shift
echo 3rd argument is %1
pause

Look at the result when we run the bat file with arguments:



No comments:

Post a Comment

Hot Topics