Page 1 of 1

Shift and %*

Posted: 06 Apr 2020 19:45
by Alogon
@echo off
echo %1
shift
echo %*

---------

If the above batch file is run with arguments 1 2 3 4, the output will be:
1
1 2 3 4

Shift does not affect the value of %*, which retains all the original arguments. What I would like is for the first argument to be a normal argument (perhaps a 'switch' like /A) that can be evaluated and removed, followed by the rest of the line treated as a single string without resorting to quotation marks. Is there a way?

Re: Shift and %*

Posted: 07 Apr 2020 03:18
by miskox

Code: Select all

shift /n
?

See shift /?

Saso

Re: Shift and %*

Posted: 08 Apr 2020 07:18
by dbenham
Unfortunately %* ignores SHIFT - it always returns the original list of parameters. There is no simple solution.

If you want to extract one or more parameters, and then pass the rest on to a subsequent program, then you must write code to iterate the parameters and build the new string of parameters yourself.

It is tempting to use something like FOR %%A IN (%*) DO ... But that is not safe because it will expand any parameters that contain * or ?

The best method is to use a GOTO loop to iterate. Something like

Code: Select all

@echo off

REM Do something with %1
shift /1

set "newParms="
:loop
set newParms=%newParms% %1
shift /1
if "%~1" neq "" goto :loop

someExe %newParms%
This still is not foolproof. It will fail if the original parameter list contains an escaped poison character (quoted poison characters are fine). It will also fail if the list contains an empty quoted value "". The loop will then end prematurely.

But this is about as good as it gets.


Dave Benham

Re: Shift and %*

Posted: 03 May 2020 10:02
by Alogon
Thanks, Dave. This is what I've done, and it works fine most of the time. Occasionally, however, there are multiple consecutive spaces in the argument which I'd want to preserve.

Re: Shift and %*

Posted: 03 May 2020 14:33
by dbenham
You can have any number of spaces in any position within an argument as long as it is quoted. In fact, the only way to have spaces within a parameter is to use quotes - it is impossible to escape spaces (or any other token delimiters like , ; = <tab> <0xFF>) because the parameter parser ignores the escape.

Re: Shift and %*

Posted: 04 May 2020 08:16
by Aacini
This method preserve original non-quoted spaces between parameters:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "all=%*"
set "restAfterFirst=!all:*%1=!"

echo All:   [%*]
echo First: [%1]
echo Rest:  [!restAfterFirst!]
Output:

Code: Select all

C:/test> test one    two     three     four
All:   [one    two     three     four]
First: [one]
Rest:  [    two     three     four]
If you use this line instead:

Code: Select all

set "restAfterFirst=!all:*%2=%2!"
Then it eliminates multiple spaces between first and second parameters only and preserve the rest (as long as first and second parameters be different)

Antonio