Page 1 of 1
SHIFT - can't get it to work in function
Posted: 23 Nov 2014 17:25
by Jer
Can you please advise me on how I can shift arguments from a prompt.
In this code, the arguments are the same after the shift.
Thanks.
Code: Select all
@Echo Off
Set /P input=Enter an integer and some text
If "%input%"=="" Then GoTo Done
Call:MyFunc %input%
::do some stuff
GoTo:Done
:MyFunc
Echo Args in function are %*
SHIFT
Echo Args after shifting are %*
:Done
Re: SHIFT - can't get it to work in function
Posted: 23 Nov 2014 17:34
by Squashman
Maybe this will help you understand how shift works.
Code: Select all
@Echo Off
Set /P input=Enter an integer and some text
If "%input%"=="" Then GoTo Done
Call:MyFunc %input%
::do some stuff
GoTo:Done
:MyFunc
Echo Args in function are %*
SHIFT
Echo Args after shifting are %*
echo %1
:Done
Output
Code: Select all
C:\Batch\Shift>shifting.bat
Enter an integer and some text1 2 3 4
Args in function are 1 2 3 4
Args after shifting are 1 2 3 4
2
Re: SHIFT - can't get it to work in function
Posted: 23 Nov 2014 17:59
by dbenham
@Jer - It is an unfortunate fact that %* is not affected by SHIFT - it always expands to all original arguments, starting with %1.
Only the expansion of numbered arguments %0, %1, %2, ... etc. are affected by SHIFT.
Dave Benham
Re: SHIFT - can't get it to work in function
Posted: 25 Nov 2014 01:21
by Jer
Thank you both for steering me in the right direction about SHIFT
to further my education in batch file coding.
This is probably common knowledge, but here is what I
worked out to parse through shifting in a function.
Jerry
Code: Select all
@Echo Off
Set strText=Hello. This is an example of parsing all text from the second word onward.
Set originalText=%strText%
Call:Parser %strText%
Echo.
Echo Original text:
Echo %originalText%
Echo.
Echo First word: %word1%
Echo All other words:
Echo %strText%
:Parser
Set word1=%1
Set strText=%2 %3 %4 %5 %6 %7 %8 %9
:Loop
SHIFT
If .%9==. GoTo:endLoop
Set strText=%strText% %9
GoTo:Loop
:endLoop
Re: SHIFT - can't get it to work in function
Posted: 25 Nov 2014 07:29
by Squashman
Here is a different way to do what you are doing without any SHIFT or GOTO.
Code: Select all
@echo off
Echo Args in function are %*
set word1=%1
FOR /F "tokens=1* delims= " %%G in ("%*") do set strtext=%%H
echo Word1 is: %word1%
echo String Text is: %strtext%
pause
Output
Code: Select all
C:\BatchFiles\SHIFTING>SHIFTING.bat Word1 Word2 Word3 Word4 Word5 Word6 Word7 Word8 Word9 Word10 Word11
Args in function are Word1 Word2 Word3 Word4 Word5 Word6 Word7 Word8 Word9 Word10 Word11
Word1 is: Word1
String Text is: Word2 Word3 Word4 Word5 Word6 Word7 Word8 Word9 Word10 Word11
Press any key to continue . . .