An answer to a previous question suggests this FOR line. Now I am trying to use the variable. My batch script at present:
@echo off
cls
for %%G in ("3D Objects","Documents","Downloads","Music","Pictures","Videos") do call :sub1 %%G
:sub1
echo %%G
set apath=%%~G
echo %apath%
goto :eof
:End
The output from this script is seven iterations of this:
%G
%~G
The subroutine seems to be doing something to the variable. Because when I substitute these lines:
for %%G in ("3D Objects","Documents","Downloads","Music","Pictures","Videos") do (
echo %%G
set apath=%%~G
echo %apath%
)
I get the desired result: six pairs of output of this nature:
"3D Objects"
3D Objects
where the tilde removes the quotation marks, as expected.
In the first code sample, the production of seven (not six) pairs of output lines suggests that the subroutine may be disregarding the quotation marks, rendering "3D" and "Objects" as two separate items — which was an issue addressed in the previous question.
I starting tinkering with the subroutine approach because I was having problems achieving a certain outcome using the simpler approach presented in the second code sample (above). Possibly delayed expansion would fix that, but at the cost of additional complexity. Not to deny that the subroutine's "goto :eof" line is also a little confusing, even if it does work.
My specific question is, what's going wrong with the variable, when used in the subroutine? But if there is a better way, I would also appreciate at least a link in that direction.
Best Answer
You are passing the value of the for loop iteration to a subroutine using call so you want to enclose that (passed variable placeholder) with a double quote and then reference the passed in variable within that subroutine as
%1
or%~1
to strip out the enclosing double quotes.Using the
GOTO :EOF
at the end of each called subroutine will pass control back to the original caller subroutine so it can continue to process the rest its logic if applicable after thecall
command.Output
Supporting Resources
Command Line arguments (Parameters)
CALL
CALL /?