0

Batch file Test.cmd:

@set args=args1
@set value=value1

@if defined value (
  @echo args: [%args%], value: [%value%]
  @set args=%args% /value=%value%
  @echo args: [%args%]
)

@echo args: [%args%]

Output of command >.\Test.cmd:

args: [args1], value: [value1]
args: [args1]
args: [args1 /value=value1]

Why do each of my calls to @echo args: [%args%] return different values? (One without the updated args value, args1, and one with the update, args1 /value=value1)

satoukum
  • 1,188
  • 1
  • 21
  • 31

1 Answers1

3

To start with, instead of using @ at the beginning of each line, just put @echo off at the very start of your script which will do the same but save you having to put @ on every line.

I would also suggest using setlocal at the begining of your scripts to avoid leavng variables defined on your system once the CMD window/script closes. It causes the variables to only be accessible for that CMD/script instance.

Try the following code and notice the echo args: [!args!]

@echo off
Setlocal EnableDelayedExpansion

set args=args1
set value=value1

if defined value (
  echo args: [%args%], value: [%value%]
  set args=%args% /value=%value%
  echo args: [!args!]
)

echo args: [%args%]

endlocal
pause

Output:

args: [args1], value: [value1]
args: [args1 /value=value1]
args: [args1 /value=value1]

Read up more about the use of EnableDelayedExpansion here...https://ss64.com/nt/delayedexpansion.html

Durry42
  • 401
  • 3
  • 10