direct swap

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Sponge Belly
Posts: 234
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

direct swap

#1 Post by Sponge Belly » 05 Feb 2013 08:18

Hello All!

Came across a post about swapping values by Joey recently. Haven’t seen anything similar elsewhere so I thought I’d share it with you. Try this out:

Code: Select all

set "fruitA=apples" & set "fruitB=bananas"
set fruit
set "fruitA=%fruitB%" & set "fruitB=%fruitA%"
set fruit


Nice trick, eh? ;-) Note that the “swap” has to be on one line and it won't work under delayed expansion.

- SB

PS: Added missing per cent. Good catch, Squashman!
Last edited by Sponge Belly on 24 Feb 2013 08:53, edited 2 times in total.

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: direct swap

#2 Post by Squashman » 05 Feb 2013 09:00

Makes logical sense according to the rules. All variables are expanded before the line is executed for normal variable expansion.

You are missing a %.

You could also write it like this.

Code: Select all

@echo off
set "fruitA=apples"
set "fruitB=bananas"
set fruit

(set "fruitA=%fruitB%"
set "fruitB=%fruitA%")
set fruit

Post Reply