Scorb
Scorb

Reputation: 1840

Batch file variable overwrite

I am creating a batch file to run a command. I set the command as follows.

set my_command=some_command %out_file%

I then run (or intended to) the command with different out_file variable

set out_file=[some_dir_1]
%my_command%

set out_file=[some_dir_2]
%my_command%

When I run the batch file, it runs my_command with out_file=[some_dir_2] twice, instead of running the first time with out_file=[some_dir_1]

Is there a way I can run the same command with different var reset everytime?

Thanks.

Upvotes: 2

Views: 2351

Answers (1)

Dennis van Gils
Dennis van Gils

Reputation: 3452

This seems to work:

@echo off
setlocal EnableDelayedExpansion
set my_command=some_command ^^!out_file^^!
set out_file=[some_dir_1]
echo %my_command%

set out_file=[some_dir_2]
echo %my_command%
pause

This works by setting the value of my_command to some_command !out_file!, so with escaped exclamation marks. When you use echo !my_command!, you'll see it contains the exclamation marks. However, when you use %my_command%, the exclamation marks get read after the % signs, so it sees another variable to expand.

You can imagine batch parsing order like this:

  1. expand variables like %var% to their value
  2. expand variables like !var! to their value

So first, the parser sees

%my_command%

which get turned into

some_command !out_file!

However, it then (it's called delayed expansion for a reason) starts checking for exclamation marks and changes that to

some_command [some_dir_2]

EDIT

Just noticed that this also works:

@echo off
setlocal EnableDelayedExpansion
set "my_command=some_command ^!out_file^!"
set "out_file=[some_dir_1]"
echo %my_command%

set "out_file=[some_dir_2]"
echo %my_command%
pause

Upvotes: 3

Related Questions