swapping the values of variable!

Hi All,

newbie here, i'm just wondering how can i swap the two values of variables without using the third variable.

Please advise,
Thanks,

One way:

$ a=5
$ b=6
$ eval $(echo a=$b\;b=$a)
$ echo $a
6
$ echo $b
5
$
1 Like

Homework?

x = x - y
y = y + x
x = y - x

1 Like

thx all.. actually exam hehe..

---------- Post updated at 06:49 AM ---------- Previous update was at 06:48 AM ----------

i don't get it.. how it is swap? can you tell me the explanation if it's ok ^^

Just for interest (using files not Enviroment Variables":

a="abcdef"
b="ghijkl"
echo "Before"
echo "a=${a}"
echo "b=${b}"
echo "${a}" >a.txt
echo "${b}" >b.txt
a="`cat b.txt`"
b="`cat a.txt`"
echo "After"
echo "a=${a}"
echo "b=${b}"

./scriptname
Before
a=abcdef
b=ghijkl
After
a=ghijkl
b=abcdef

Another way - append to $a with a delimiter:

a="abcdef"
b="ghijkl"
echo "Before"
echo "a=${a}"
echo "b=${b}"
a="${a}:${b}"
b=`echo "${a}"|awk -F: '{print $1}'`
a=`echo "${a}"|awk -F: '{print $2}'`
echo "After"
echo "a=${a}"
echo "b=${b}"

./scriptname
Before
a=abcdef
b=ghijkl
After
a=ghijkl
b=abcdef
2 Likes

Initially, x = 3, y = 2
x = x - y # Capture the difference of two variables in x --> x = 3 - 2 = 1
y = y + x # Add the difference to y to get the initial value of x --> y = 2 + 1 = 3
x = y - x # Subtract the difference from y to get the initial value of y --> x = 3 - 1 = 2

Finally, x = 2, y = 3.

But this won't work for variables containing string values. In such cases, you'd have to go for methods as suggested by methyl.