Reply to comment

Batch tricks: Swapping values

A common task in many algorithms is swapping two values. Usually implentations take the form
temp := a;
a := b;
b := temp;

In some languages (such as Python or Lua) you may also write the following:

a, b = b, a

And a method similar to this one is even possible in batch files.

Since variable substitution in CMD is done while the line is parsed (for backwards compatibility) except when using ! instead of % we can use this to our advantage and swap to values in one line without resorting to a temporary variable:

set A=%B%&set B=%A%

Be careful not to use a space before the & to avoid having that space character in your value (if this is critical).

And the use of % here is also important. Since delayed expansion (done with ! expands when the value is used the code set A=!B!&set B=!A! will set both A and B to the value of B.

Reply

The content of this field is kept private and will not be shown publicly.