Problem passing parameters by ref in for /R

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
einstein1969
Expert
Posts: 941
Joined: 15 Jun 2012 13:16
Location: Italy, Rome

Problem passing parameters by ref in for /R

#1 Post by einstein1969 » 22 Nov 2023 05:10

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


IcarusLives
Posts: 162
Joined: 17 Jan 2016 23:55

Re: Problem passing parameters by ref in for /R

#2 Post by IcarusLives » 22 Nov 2023 07:08

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

mataha
Posts: 32
Joined: 27 Apr 2023 12:34

Re: Problem passing parameters by ref in for /R

#3 Post by mataha » 22 Nov 2023 07:55

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 ...

einstein1969
Expert
Posts: 941
Joined: 15 Jun 2012 13:16
Location: Italy, Rome

Re: Problem passing parameters by ref in for /R

#4 Post by einstein1969 » 22 Nov 2023 12:33

Thank you both. I hadn't gotten there.

Post Reply