user2545157
user2545157

Reputation: 111

Setting value in a variable in batch file

How to set value of %%~nm to a variable. [ie] when I try to set it like Set "var=%%~nm" and echo %var% .Output is giving empty string I am facing this issue for all values which has ~. Kindly provide a solution .

Upvotes: 0

Views: 337

Answers (2)

Endoro
Endoro

Reputation: 37569

try this (new variables can't be used in the same for loop without delayed expansion:

for %%m in (*) do call:doit "%%~nm"
goto:eof

:doit
set "var=%~1"
echo %var%
goto:eof

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

echo %var% should work fine when used outside the for loop. When you want to echo a variable inside a for loop, you have to enable delayed expansion and use !var! (variable is expanded at runtime) instead of %var% (variable is expanded at parsetime):

@echo off

setlocal EnableDelayedExpansion

for %%m in (*) do (
  set "var=%%~nm"
  echo !var!
)

echo %var%

endlocal

If you want to compare a variable to a string, you have to put either both between quotes or none:

if %var%==string ...

or

if "%var%"=="string" ...

Otherwise you'd be comparing string=="string", which are obviously not equal.

Upvotes: 0

Related Questions