Some test cases which fail most naive counting approaches would be...
- " --- expected count 1
- "" a --- 2
- a " b --- 2
Thanks,
Liviu
Moderator: DosItHelp
Code: Select all
@echo off
set count=0
for %%I in (%*) do IF NOT "%%~I"=="" set /a count+=1
echo %count%
Liviu wrote:Is there a way to reliably get the count of arguments a batch file was called with, safe against odd inputs, and preferably without invoking external programs or temp files?
Squashman wrote:Don't think there is much you could do about a string not being closed quoted correctly. If you just have a set of empty quotes then you can check to see if it is empty.
So given your example of "" a ---
aGerman wrote:I'm afraid the answer is NO.
REM is the only command that is able to catch the arguments %* as is.
Code: Select all
set "x=%*#"
setlocal EnableDelayedExpansion
if "!x:~1,1!"=="" (endlocal &set "x=0") else (endlocal &set x=1)
echo %x%
aGerman wrote:I'm not sure whether this would work in each case:
Code: Select all
set "x=%1"
setlocal EnableDelayedExpansion
if defined x (endlocal &set x=1) else (endlocal &set x=0)
echo %x%
Liviu wrote:The above looks at %1 instead of %*. Off topic somewhat, but it is possible that %1 is not present, but %* is still not empty, for example when passing a separators-only command line such as ;,=.
Code: Select all
@echo off
setlocal enableDelayedExpansion
set argCnt=1
:getArgs
>"%temp%\getArg.txt" <"%temp%\getArg.txt" (
setlocal disableExtensions
set prompt=#
echo on
for %%a in (%%a) do rem . %1.
echo off
endlocal
set /p "arg%argCnt%="
set /p "arg%argCnt%="
set "arg%argCnt%=!arg%argCnt%:~7,-2!"
if defined arg%argCnt% (
set /a argCnt+=1
shift /1
goto :getArgs
) else set /a argCnt-=1
)
del "%temp%\getArg.txt"
set arg
Code: Select all
setlocal DisableDelayedExpansion &prompt $
>"%temp%\x.txt" (
echo on &for %%i in (1) do rem %*#
)
@prompt &endlocal &setlocal EnableDelayedExpansion &echo off
<"%temp%\x.txt" (for %%i in (1 2) do set /p "x=")
del "%temp%\x.txt"
if "!x:~4,-2!"=="" (endlocal &set x=0) else (endlocal &set x=1)
echo %x%
aGerman wrote:It's still not exactly foolproof
Example argument (jeb):
one^&two"&three
simplified:
"& or "&"
dbenham wrote:Here is a clean looking script that safely loads all of the arguments into an arg "array" using the REM trick.
dbenham wrote:Now I understand why jeb had that # in his REM statement, to protect against /?
I've edited my previous post to compensate.
Code: Select all
for %%a in (%%a) do rem . %1.