Page 1 of 1

use for loop to set local variable

Posted: 16 Dec 2019 05:18
by Gunner
Hi

Within my .bat file I want to get the name of the only file in a folder (I am guaranteed that there will only ever be 1 file)

I have tried this

Code: Select all

set fn="a"
for /r %%i in (*) do set %fn% = %%~nxi
but fn is not set as expected

First question: why not and how can I fix
Second question : this seems a clunky solution - is there a better way

Re: use for loop to set local variable

Posted: 16 Dec 2019 05:34
by aGerman

Code: Select all

for /r %%i in (*) do set "fn=%%~nxi"
No need to define variable fn beforehand. Using %fn% in the assignment is probably not what you wanted, use the variable name instead of the variable value. Omit the spaces around the equal sign because they would lead to variable names having a space appended and its value having a space prepended. Surrounding quotation marks in the assignment will protect you from problems with special characters such like & in a file name.
If you don't have to search recursively in subfolders you don't need option /r and you don't need the ~nx modifier to remove the path. And note that you will always find your own batch file the way the code is currently written, because you didn't specify a different path where to search files.

Steffen

Re: use for loop to set local variable

Posted: 16 Dec 2019 07:27
by Gunner
Thanks for the reply and explanation - all working nowq