views:

314

answers:

1

There have been a lot of questions asked and answered about batch file parameters with regards to the %* but I haven't found an answer for this.

Is there an equivalent syntax in batch files that can perform the same behavior as "$@" in unix.

Some context:

@echo off
set MYPATH=%~dp0
set PYTHON=%MYPATH%..\python\python
set BASENAME=%~n0
set XTPY=%MYPATH%..\SGTools\bin\%BASENAME%.py
"%PYTHON%" "%XTPY%" %*

This is the .bat file that is being used a proxy to call a python script. So I am passing all the parameters (except the script name) to the python script. This works fine until there is a parameter in quotes and/or contains spaces.

In shell scripts you can use "$@" to take each parameter and enclose it in quotes. Is there something I can do to replicate this process?

Example Calls:

xt -T sg -t "path with possible spaces" -sum "name with spaces" -p <tool_name> -o lin32 lin64 win32 <lots of other options with possibilities of spaces>

The command/file xt simply contains the code listed above because the actual executable is python code in a different folder. So the point is to create a self-contained package where you only add 1 directory (xbin directory) to your path.

+1  A: 

This was driving me nuts too. I'm not sure what the cleanest solution is, but here is how I worked around the problem:

setlocal EnableDelayedExpansion    
for %%i in (%*) do set _args= !_args! "%%~i"    
echo %_args%

%_args% will now contain a quoted list of each individual parameter. For example, if you called the batch file as follows:

MYBATFILE "test'1'file" "test'2'file" "test 3 file"`

echo %_args%

will produce the original quoted input.

I needed this for CMD files that take unfriendly file or directory names and pass them to cygwin bash shell scripts which do the heavy lifting, but I couldn't afford to have the embedded single quotes or spaces lost in the transition.

Note the ~i in %%~i% which is necessary to remove quotes before we apply quotes. When a parameter containing spaces is passed (e.g., "test 3 file" above), the CMD shell will already have applied quotes to it. The tilde here makes sure that we don't double-quote parameters containing spaces.

Hope this helps!