8

I need to get last argument passed to windows batch script, how can I do that?

Martin G
  • 17,357
  • 9
  • 82
  • 98
Jarek
  • 7,425
  • 15
  • 62
  • 89
  • See [here](http://stackoverflow.com/questions/357315/get-list-of-passed-arguments-in-windows-batch-script-bat) – Ken White Apr 27 '11 at 14:00

4 Answers4

12

This will get the count of arguments:

set count=0
for %%a in (%*) do set /a count+=1

To get the actual last argument, you can do

for %%a in (%*) do set last=%%a

Note that this will fail if the command line has unbalanced quotes - the command line is re-parsed by for rather than directly using the parsing used for %1 etc.

Random832
  • 37,415
  • 3
  • 44
  • 63
10

The easiest and perhaps most reliable way would be to just use cmd's own parsing for arguments and shift then until no more are there.

Since this destroys the use of %1, etc. you can do it in a subroutine:

@echo off
call :lastarg %*
echo Last argument: %LAST_ARG%
goto :eof

:lastarg
  set "LAST_ARG=%~1"
  shift
  if not "%~1"=="" goto lastarg
goto :eof
Joey
  • 344,408
  • 85
  • 689
  • 683
1

An enhanced version of joey's answer:

@ECHO OFF
SETLOCAL

:test
    :: https://stackoverflow.com/a/5807218/7485823
    CALL :lastarg xxx %*
    ECHO Last argument: [%XXX%]
    CALL :skiplastarg yyy %*
    ECHO skip Last argument: [%yyy%]
GOTO :EOF

:: Return all but last arg in variable given in %1
:skiplastarg returnvar args ...
    SETLOCAL
        SET $return=%1
        SET SKIP_LAST_ARG=
        SHIFT
    :skiplastarg_2
        IF NOT "%~2"=="" SET "SKIP_LAST_ARG=%SKIP_LAST_ARG% %1"
        SHIFT
        IF NOT "%~1"=="" GOTO skiplastarg_2
    ENDLOCAL&CALL SET "%$return%=%SKIP_LAST_ARG:~1%"
GOTO :EOF

:: Return last arg in variable given in %1
:lastarg returnvar args ...
    SETLOCAL
      SET $return=%1
      SET LAST_ARG=
  SHIFT
    :LASTARG_2
      SET "LAST_ARG=%1"
      SHIFT
      IF NOT "%~1"=="" GOTO lastarg_2
    ENDLOCAL&call SET %$return%=%LAST_ARG%
GOTO :EOF

Run it with the arguments:

abe "ba na na" "cir cle"

and get:

Last argument: ["cir cle"]

skip Last argument: [abe "ba na na"]

  • Thank you, sometimes it helps to process just the last couple of arguments differently but pass on the rest as is – Enno Apr 13 '22 at 12:41
0
set first=""
set last=""
for %%a in (%*) do (
SETLOCAL ENABLEDELAYEDEXPANSION
if !first!=="" (set first=!last!) else (set first=!first! !last!)
set last=%%a

)
ENDLOCAL & set "last=%last%" & set "first=%first%"
echo %last%  "and" %first%
mohan raj
  • 31
  • 3