Wednesday, April 13, 2005

Batch job argument ramblings

You have to learn something new every day. I just did that again today. I learnt two things –
  1. shift has not influence on %*
  2. getting rid of quotes in arguments can be done in an easier way than I used to – or can it?
Take this example: I want to execute a bat file, use the two first arguments and collapse the rest into one. Thought I could do it with:
Set arg1=%1
Set arg2=%2
Set rest=%*
But no – does not work :(

Used to get rid of quotes with
Set arg=%1
Set arg=%arg:"=%

Found in the help, that it can be done with
Set arg=%~1
And I was happy to find an easier way but only for a short while. If there are embedded quotes it does not work, so my old method is still the best :)

If you are not aware of the other stuff %~ can do, consult Help and Support Center on your PC. A useful feature is this:
Set BatFileDirectory=%~dp0
Copy "%BatFileDirectory%\somefile.exe" somewhere

Back to the %*. How can it be done? Try this – other clever ways are welcome –
set arg1=%1
set arg2=%2
set rest=
set onevalue=%3
if defined onevalue (
if defined rest (

set rest=%rest% %~3
) else (
set rest=%~3
shift /3
goto restloop
set rest=%rest:"=%
A warning: If the input contains parenthesis, you have to make a goto-based implementation instead of the multi-line if.

No comments: