Batch script forwarding arguments with double quotes

Imagine that you have a program foo.exe which takes multi-word command line arguments, for example

$>foo.exe aShortArg aKey:"multi-word arg"
arg1 = aShortArg
arg2 = aKey:"multi-word arg"

You also have a timing script timer.scala (could also be written in Java) which runs another program and measures its runtime. To facilitate starting the script you have written a batch file which runs the actual script.

// timer.bat
@echo off
SetLocal
 
set CP=.;%SCALA_HOME%\lib\scala-library.jar
set JAVA_OPTS=%JAVA_OPTS% -Xss16m
 
call java %JAVA_OPTS% -cp "%CP%" TimerMain %*

In order to not worry about properly escaping double quotes when passing them to timer.bat, .e.g

$>timer.bat bbb.exe path\to\aaa.exe aKey:"multi-word arg"
Starting benchmark ...
Running aaa.exe at path\to:
arg1 = aKey:multi-word
arg2 = arg
... DONE
Runtime: 1s
 
$>timer.bat bbb.exe path\to\aaa.exe aKey:"\"multi-word arg\""
Starting benchmark ...
Running aaa.exe at path\to:
arg1 = aKey:"multi-word arg"
... DONE
Runtime: 1s

you can change timer.bat such that double quotes get escaped automatically before they are forwarded:

// timer.bat
@echo on
SetLocal EnableDelayedExpansion
 
set ARGS=
 
:parse_args
if not %1.==. (
  set ARG=%1
  set ARGS=!ARGS! ^"!ARG:"=\"!^"
  shift
  goto :parse_args
)
 
set CP=.;%SCALA_HOME%\lib\scala-library.jar
set JAVA_OPTS=%JAVA_OPTS% -Xss16m
 
call java %JAVA_OPTS% -cp "%CP%" TimerMain %ARGS%

This also you to forget about escaping double quotes, and enables you to simply specify the arguments to foo as if they were direct arguments, i.e. as if they would not be looped through the timer script:

$>timer.bat bbb.exe path\to\aaa.exe aKey:"multi-word arg"
Starting benchmark ...
Running aaa.exe at path\to:
arg1 = aKey:"multi-word arg"
... DONE
Runtime: 1s

Leave a Reply

Your email address will not be published. Required fields are marked *

*