views:

258

answers:

3

Greetings, dear Experts!

I want to check the existense of parameter (or argument) sting at all in my batch script:

if "%*"=="" findstr "^::" "%~f0"&goto :eof

This works fine if none of parameters is enclosed in double quotes. For example:

test.bat par1 par2 ... --- works

but

test.bat "par 1" par2 ... --- fails

My question are:

1) Is there any way to overcome this instead of requirement for use to use non-double-quoted symbol to specify "long" arguments and then use string substitution?

2) Can I ever use "if" to compare two strings containing both double quotes and spaces?

Your prompt and clear reply would be very much appreciated.

+1  A: 

~ will strip the double quotes, but does not work on %*, but if you just want to know if there are no parameters, just checking %1 should be enough

if "%~1"==""

You might want to call setlocal ENABLEEXTENSIONS first to make sure extensions are on (required for ~)

Anders
A: 

Thank you, Andres. Here are two more pieces of code to check the existence and number of passed parameters:

set ArgumentString=%*
if not defined ArgumentString findstr "^::" "%~f0"&goto :eof
if "%ArgumentString:"=%"=="" findstr "^::" "%~f0"&goto :eof


set NumberOfArguments=0
for /l %%N in (1,1,9) do (
  call set CurrentArgument=%%%%N
  if defined CurrentArgument set /a NumberOfArguments += 1
)
if %NumberOfArguments% NEQ %N% findstr "^::" "%~f0"&goto :eof

Here variable N contains needed number of parameters.

Hope this helps for somebody!

Andrey
The latter way fails to count correctly with more than 9 arguments.
Joey
Thank you, Johannes!However your method does not correctly process arguments with spaces, such as "aaa bbb"...
Andrey
A: 

Since Andrey's answer fails to correctly count arguments, here is a way that does work, even with more than 9 arguments (and it even perserves the original ones, so %1 still points to the first one by moving the shifting into a subroutine):

@echo off
call :get_num_args %*
echo %NumArgs%
goto :eof

:get_num_args
  set NumArgs=0
  :loop
  if not [%1]==[] (set /a NumArgs+=1) else (goto :eof)
  shift
  goto loop
goto :eof
Joey