Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch For loop to get first value

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.

like image 853
TBrenner Avatar asked Dec 09 '25 22:12

TBrenner


1 Answers

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
like image 71
MC ND Avatar answered Dec 11 '25 13:12

MC ND



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!