Search code examples
batch-fileif-statementdelayedvariableexpansion

Assigning a variable inside if loop : Windows Bat script


I'm trying to write a bat script and faced the following issue.

Below is the snippet with which the issue is dealt with.

setlocal enabledelayedexpansion enableextensions
@echo off
@echo:
echo Select an option:
echo *****************
@echo:
echo 1) process 2gen files
@echo:
echo 2) process 3gen files
@echo:
set /p option=Enter option number : %=%

set fileName=nil
echo %option%
if %option% == 1 (
set fileName = 2gen
echo !fileName!
)
echo !fileName!

The output of this bat script is as follows:

Select an option:
*****************

1) process 2gen files

2) process 3gen files

Enter option number : 1
1
nil
nil

i'm expecting the echo for fileName to have value 2gen but it is still printing nil

In my first attempt, i didn't use the setlocal enabledelayedexpansion enableextensions and !fileName! (instead used %fileName%)

After searching for solution enabled the delayed expansion. But still couldn't get what the exact mistake is.

Also the OS version being used is Windows 7 64 bit

Please help me in pointing out the mistake.

Thanks!


Solution

  • set fileName = 2gen sets a variable named filename<space> to a value <space>2gen. Get rid of the spaces. Even better, use this recommended syntax:

    set "variable=value"
    

    to avoid unintended trailing spaces.

    (of course you could use echo !filename !...)