Page 1 of 1

Problem passing parameters by ref in for /R

Posted: 22 Nov 2023 05:10
by einstein1969
Hi,

I have this problem

The first procedure create_folder0 with parameters by value work

The second create_folder1 with name of variable don't work

It simple but i don't know where I worng :(

Code: Select all

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off
setlocal EnableDelayedExpansion

set "Origin=J:\Video\Generi_Video"


	call :create_folders0 "!Origin!"
pause
	call :create_folders1 Origin

pause


goto :eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
SUBS

:create_folders0

	for /R "%~1" %%D in (*.*) do echo working...

echo "%~1"


goto :eof

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:create_folders1

	for /R "!%~1!" %%D in (*.*) do echo working...

echo "!%~1!"


goto :eof


Re: Problem passing parameters by ref in for /R

Posted: 22 Nov 2023 07:08
by IcarusLives
The only way I could solve it was like this

Code: Select all

:create_folders1

	set "param=!%~1!"
	for /R "%param%" %%D in (*.*) do echo working...

echo "!%~1!"


goto :eof
I'm not 100%, but I think it's because of the order of which things are happening, and I think the step which variable expansion happens, happens too late, therefore not giving you the output loop you're expecting, but if you expand it before the loop, it ends up working. Or maybe I'm all wrong, and I don't understand the problem very well haha

Re: Problem passing parameters by ref in for /R

Posted: 22 Nov 2023 07:55
by mataha
Regarding for /r: there is no tokenization involved as far as the first argument (directory) is concerned; if there are leading and trailing quotes by the time cmd has finished parsing the line, they are stripped. That's it.

If you want to use a variable there, it has to be expanded eagerly (i.e. via %):

Code: Select all

set "param=!%~1!"
for /r "%param%" %%d in (*.*) do ...
Note that for /f behaves in a similar manner (trivia: for /f options are stored in the same union), so the following won't work:

Code: Select all

set "options=usebackq tokens=1,*"
for /f "!options!" %%x in (`echo a`) do ...
But this will:

Code: Select all

set "options=usebackq tokens=1,*"
for /f "%options%" %%x in (`echo a`) do ...

Re: Problem passing parameters by ref in for /R

Posted: 22 Nov 2023 12:33
by einstein1969
Thank you both. I hadn't gotten there.