batch-filewindows-xp

How to make SHIFT work with %* in batch files


In my batch file on Windows XP, I want to use %* to expand to all parameters except the first.
Test file (foo.bat):

@echo off
echo %*
shift
echo %*

Call:

C:\> foo a b c d e f

Actual result:

a b c d e f
a b c d e f

Desired result:

a b c d e f
b c d e f

How can I achieve the desired result? Thanks!!


Solution

  • Wouldn't it be wonderful if CMD.EXE worked that way! Unfortunately there is not a good syntax that will do what you want. The best you can do is parse the command line yourself and build a new argument list.

    Something like this can work.

    @echo off
    setlocal
    echo %*
    shift
    set "args="
    :parse
    if "%~1" neq "" (
      set args=%args% %1
      shift
      goto :parse
    )
    if defined args set args=%args:~1%
    echo(%args%
    

    But the above has problems if an argument contains special characters like ^, &, >, <, | that were escaped instead of quoted.

    Argument handling is one of many weak aspects of Windows batch programming. For just about every solution, there exists an exception that causes problems.