How to undo SHIFT effect

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ernest211
Posts: 6
Joined: 14 Jun 2010 06:20

How to undo SHIFT effect

#1 Post by ernest211 » 16 Jun 2010 07:28

How can I undo Shift effect of course if it possible. What do I mean, I’m executing my script passing two or more arguments and in this script I have shift so my first argument will be equals what I pass as second argument. Now when method with shift will end I wan to undo shift effect.

e.g.
I have script “test.bat” and I’m running him “test.bat param1 param2 param3”
script code

Code: Select all

@ECHO OFF
echo start: %1

:Loop
IF "%2"=="" GOTO Continue   
   echo %2   
SHIFT
GOTO Loop
:Continue

echo end: %1


So script must display on de beginning “param1” and also on the end but now he displaying "param1" and nothing on the end.
How can I do this?

amel27
Expert
Posts: 177
Joined: 04 Jun 2010 20:05
Location: Russia

Re: How to undo SHIFT effect

#2 Post by amel27 » 16 Jun 2010 07:46

ernest211 wrote:So script must display on de beginning “param1” and also on the end but now he displaying "param1" and nothing on the end.
How can I do this?
it's not undo shift, but with same result (preserve original params):

Code: Select all

@echo off
echo start: %1
call :loop %*

echo end: %1
goto :eof

:loop
if "%2"=="" goto :eof
echo %2
shift
goto loop

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: How to undo SHIFT effect

#3 Post by avery_larry » 16 Jun 2010 09:59

I would suggest you try and avoid using shift completely if you might need the parameters later in your script.

2 ideas for you:

1) Specific to the code you have shown, you could use a for loop:

Code: Select all

@ECHO OFF
echo start: %1
for %%a in (%*) do echo %%a
echo end: %1


2) You can use a for loop to go through all the parameters, and assign them all to variables. These variables would then be used in the rest of your code:

Code: Select all

@ECHO OFF
setlocal enabledelayedexpansion
set idx=0
for %%a in (%*) do (
   set /a idx+=1
   set param!idx!=%%a
)
echo There were %idx% parameters passed.
echo Start: %param1%
for /l %%a in (2,1,%idx%) do echo.!param%%a!
echo End:  %param1%


so param1 = %1, param2 = %2, param3 = %3 etc.

or the same using shift to assign variables and the "call" trick to avoid delayedexpansion:

Code: Select all

@echo off
set idx=0
echo Start: %1

:loop
set /a idx+=1
set param%idx%=%1
shift
if not "%1"=="" goto :loop
for /l %%a in (2,1,%idx%) do call echo.%%param%%a%%
echo End: %param1%

Post Reply