Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable in "if" block

The following program always echoes "machine-abc" in the end:

@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
 %dropLoc% = machine-xyz
) 
echo %dropLoc%

Is this a scope issue? Does the dropLoc variable in the if statement have a different scope? I have tried the following to address the issue:

@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
 !dropLoc! = machine-xyz
) 
echo %dropLoc%

and

@echo Off
set dropLoc=machine-abc
IF %computername% == "xyz" (
 set dropLoc = machine-xyz
) 
echo %dropLoc%

How do I make this work?

like image 532
coder_bro Avatar asked Oct 18 '11 10:10

coder_bro


1 Answers

You got the SET syntax right the first time, how come you decided to write something else the second time round? Also, you have to add the quotation marks on both sides of the comparison. Unlike in other script interpreters, quotation marks aren't special for the batch interpreter.

@echo off

rem Change this for testing, remove for production
set computername=xyz

set dropLoc=machine-abc

if "%computername%" == "xyz" (
  set dropLoc=machine-xyz
)

echo %dropLoc%
like image 170
Kerrek SB Avatar answered Oct 19 '22 23:10

Kerrek SB