0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Swap Two Numbers Easily

In Bash, you can swap two numbers using a temporary variable like this: temp=$a; a=$b; b=$temp.
📋

Examples

Inputa=5, b=10
Outputa=10, b=5
Inputa=0, b=0
Outputa=0, b=0
Inputa=-3, b=7
Outputa=7, b=-3
🧠

How to Think About It

To swap two numbers, store the value of the first number in a temporary place, then assign the second number's value to the first, and finally assign the temporary stored value to the second number. This way, no data is lost during the swap.
📐

Algorithm

1
Get the values of the two numbers.
2
Store the first number in a temporary variable.
3
Assign the second number's value to the first number.
4
Assign the temporary variable's value to the second number.
5
Print the swapped values.
💻

Code

bash
#!/bin/bash

a=5
b=10

echo "Before swap: a=$a, b=$b"

temp=$a
 a=$b
 b=$temp

echo "After swap: a=$a, b=$b"
Output
Before swap: a=5, b=10 After swap: a=10, b=5
🔍

Dry Run

Let's trace swapping a=5 and b=10 through the code

1

Initial values

a=5, b=10

2

Store a in temp

temp=5

3

Assign b to a

a=10

4

Assign temp to b

b=5

VariableValue
a5
b10
temp5
a10
b5
💡

Why This Works

Step 1: Use a temporary variable

We use temp to hold the value of a so it is not lost when we overwrite a.

Step 2: Assign second number to first

We set a=$b to put the second number's value into a.

Step 3: Restore first number to second

Finally, we assign b=$temp to complete the swap.

🔄

Alternative Approaches

Using arithmetic without temp variable
bash
#!/bin/bash

a=5
b=10

echo "Before swap: a=$a, b=$b"

a=$((a + b))
b=$((a - b))
a=$((a - b))

echo "After swap: a=$a, b=$b"
This method swaps numbers without extra memory but can cause overflow with very large numbers.
Using read and echo for user input
bash
#!/bin/bash

echo "Enter first number:"
read a
echo "Enter second number:"
read b

echo "Before swap: a=$a, b=$b"

temp=$a
a=$b
b=$temp

echo "After swap: a=$a, b=$b"
This approach allows swapping numbers entered by the user interactively.

Complexity: O(1) time, O(1) space

Time Complexity

Swapping two numbers uses a fixed number of operations, so it runs in constant time O(1).

Space Complexity

Only a few variables are used, so space complexity is constant O(1).

Which Approach is Fastest?

Both the temporary variable and arithmetic methods run in O(1) time, but the temporary variable method is safer and clearer.

ApproachTimeSpaceBest For
Temporary variableO(1)O(1)Safe and clear swapping
Arithmetic methodO(1)O(1)No extra variable but risk of overflow
User input methodO(1)O(1)Interactive swapping with user input
💡
Always use a temporary variable to avoid losing data when swapping values.
⚠️
Trying to swap without a temporary variable or arithmetic can overwrite values and lose data.