2
votes

I'm writing a batch file and I want to run a for loop that sets it's first value to a variable. I only need the first value of a command but I couldn't find another way to do this. The way I have it set up is with a for loop then a do statement that says if variable is not set, set variable. The issue is when this runs, the loop uses the unset variable every time instead of treating it as set after the first loop.

For example, my if says if "%foo%"=="" set foo=%%i and the output looks like this if "" == "" set foo="hello" the next loop will still say if "" == "" set foo="bar"

Is there a way to get around this? I tried setting delayed expansion and that didn't help. I'm also open to other ways that will give me only the first value from a command.

1
Please put here what you've tried so far. - mihai_mandis
Delayed expansion would have worked if you enabled it, and changed %foo% to !foo! - dbenham
Answer below worked. I tried with delayed expansion with ! but I may have had to use more escape characters. - TBrenner

1 Answers

6
votes
set "foo="
for /f %%i in (....) do if not defined foo set "foo=%%i"

Or, if you can add a label

for /f %%i in (....) do set "foo=%%i" & goto :done
:done