How to use %0, %1, %2, etc. and the SHIFT command

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Cat
Posts: 32
Joined: 11 Nov 2011 12:04

How to use %0, %1, %2, etc. and the SHIFT command

#1 Post by Cat » 27 Nov 2011 14:23

How do I use and set replaceable parameters such as %1 in batch?
How does the SHIFT command work with these?

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: How to use %0, %1, %2, etc. and the SHIFT command

#2 Post by Ed Dyreen » 27 Nov 2011 15:00

'

Code: Select all

@echo off

call :func "par am1" par am2
pause

for /? |more
exit /b 0

:func
::(
   echo.%*
   echo.1=%1_, 1=%~1, 2=%2_
   shift
   echo.1=%1_, 1=%~1, 2=%2_
::)
exit /b 0

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

Re: How to use %0, %1, %2, etc. and the SHIFT command

#3 Post by orange_batch » 29 Nov 2011 02:44

Arguments (%0, %1-9) are set when calling upon a batch script.

%0 always represents the source of the script (unless shifted over), %1-9 the accessable arguments passed to it, and anything beyond it requires the shift command.

There are only two ways to pass arguments to a batch script. Straight from the command line,

Code: Select all

myscript.bat arg1 "arg 2"

or within a script, using call (so the originating script can be returned to) to run another script file or a labelled subroutine,

Code: Select all

call anotherscript.bat arg1 "arg 2"

call :subroutine arg1 "arg 2"

So if you need to pass more than 9 arguments, shift will do this:

Code: Select all

myscript.bat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Code: Select all

echo %0
echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:: Outputs:
:: (Full Path)\myscript.bat
:: 1 2 3 4 5 6 7 8 9

shift

echo %0
echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:: Now output is:
:: 1
:: 2 3 4 5 6 7 8 9 10

Don't want to lose %0, or want to shift at a specific argument? No problem.

Code: Select all

echo %0
echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:: Outputs:
:: (Full Path)\myscript.bat
:: 1 2 3 4 5 6 7 8 9

shift /1

echo %0
echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:: Now output is:
:: (Full Path)\myscript.bat
:: 2 3 4 5 6 7 8 9 10

shift /5

echo %0
echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:: Now output is:
:: (Full Path)\myscript.bat
:: 2 3 4 6 7 8 9 10 11

The number you write after shift is the argument number that is shifted onto.

Post Reply