Get last command line argument in windows batch file
I need to get last argument passed to windows batch script, how can I do that?
Solution 1:
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
Solution 2:
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.