Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Trying to use the Call SET to set a variable in a windows batch file loop. Not working but here is the input / output file. trying to assign Var C to equal 1.

Batch file:

 @ECHO OFF
for /f "tokens=1-3 delims=," %%a in (Puck.csv) do (

echo Hello No Hockey>%%a.txt

echo #:A %%a>>%%a.txt

echo #:B %%b>>%%a.txt

if /I %%c gtr 10 call set %%c==1

echo #:C %%c>>%%a.txt

)

Puck.csv

1991,NHL Strike,20

1992,NHL Strike,20

1993,NHL Strike,20

OutPut:

Hello No Hockey
#:A 1991
#:B NHL Strike
#:C 20
Hello No Hockey
#:A 1992
#:B NHL Strike
#:C 20
Hello No Hockey
#:A 1993
#:B NHL Strike
#:C 20

share|improve this question
 @ECHO OFF
setlocal enabledelayedexpansion
for /f "tokens=1-3 delims=," %%a in (Puck.csv) do (
echo Hello No Hockey>%%a.txt
echo #:A %%a>>%%a.txt
echo #:B %%b>>%%a.txt
set c=%%c
if /I !c! gtr 10 set c=1
echo #:C !c!>>%%a.txt
)

Just lookup enabledelayedexpansion and learn when and how to use it (with ! instead of %).
Also, there is no need to use call when resetting c (using a single =).

share|improve this answer

You have 2 problems:

1) You are confusing FOR variables with environment variables. A batch FOR variable name is always a single character, and it is access via 2 percents prior to the name: %%c. A FOR variable value cannot be changed with SET.

An environment variable name can contain multiple characters, though it can be a single character, and it is accessed by enclosing the name in percents: %var%. Exclamation points can be used if you want delayed expansion: !var!. An environment variable value is set with SET.

2) The CALL trick to access environment variable values that were set within a parenthesized code block is used at expansion time, not when you are setting the value.

I believe mousio provided provided the best answer; I always use delayed expansion like in that answer. But it is possible to do what you want without delayed expansion by properly using an environment variable and the CALL trick.

@echo off
for /f "tokens=1-3 delims=," %%a in (Puck.csv) do (
  echo Hello No Hockey>%%a.txt
  echo #:A %%a>>%%a.txt
  echo #:B %%b>>%%a.txt
  set C=%%c
  if /i %%c gtr 10 set C=1
  call echo #:C %%C%%>>%%a.txt
)

Note that it is critical that the case of the FOR variable is different than the environment variable. FOR variables are case sensitive, environment variables are not. If you use c for both, then the parser will treat %%c%% as the FOR variable followed by a percent - not what you want.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .