Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
Jarek Avatar asked Apr 27 '11 13:04

Jarek


People also ask

What are batch-file command line arguments?

batch-file Batch file command line arguments 1 Command line arguments supplied to batch files 2 . Batch file command line arguments are parameter values submitted when... 3 Batch files with more than 9 arguments#N# 4 . When more than 9 arguments are supplied, the shift n] command can be used,...*Shifting arguments inside brackets#N##. *]More ...

How to get last argument passed to Windows batch script?

I need to get last argument passed to windows batch script, how can I do that? 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:

How to get the value of any argument in a batch?

But before solving this problem I want to introduce with batch parameter. In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on.

How to get the value of a command line argument?

A command line argument (or parameter) is any value passed into a batch script: C:> MyScript.cmd January 1234 "Some value" Arguments can also be passed to a subroutine with CALL: CALL :my_sub 2468 You can get the value of any argument using a % followed by it's numerical position on the command line.


2 Answers

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
like image 136
Joey Avatar answered Oct 18 '22 16:10

Joey


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.

like image 31
Random832 Avatar answered Oct 18 '22 14:10

Random832