Linux shell script program to swap two numbers

By IncludeHelp Last updated : October 20, 2024

Problem statement

Here, we will create a shell script program to swap to numbers and then print both variables after swapping on the console screen.

Swap two numbers using Linux Shell Script

The source code to create a Linux shell script program to swap two numbers is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

Linux shell script program to swap two numbers

#!/bin/bash

# Program name: "swap.sh"
# shell script program to swap two numbers.

num1=10
num2=20

echo "Before Swapping"
echo "Num1: $num1"
echo "Num2: $num2"

num3=$num1
num1=$num2
num2=$num3

echo "After Swapping"
echo "Num1: $num1"
echo "Num2: $num2"

Now we will save the shell script program with the "swap.sh" name.

Output

$ sh swap.sh 
Before Swapping
Num1: 10
Num2: 20
After Swapping
Num1: num2
Num2: num3

Explanation

In the above program, we created two variables num1 and num2 that are initialized with 10 and 20 respectively. Here, we interchanged the values of both variables using variable num3 and then print both variables on the console screen.

Linux shell script programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.