Bash shell script to swap two numbers
Given two numbers and the task is to swap them using the third variable. Examples:
Input: first = 2, second = 4
Output: first = 4, second = 2
Input: first = 5, second = 7
Output: first = 7, second = 5
Approach:
- Store the value of the first number into a temp variable.
- Store the value of the second number in the first number.
- Store the value of temp into the second variable.
#!/bin/bash
# Program to swap two numbers
# Static input of the
# numbers
first=5
second=10
temp=$first
first=$second
second=$temp
echo "After swapping, numbers are:"
echo "first = $first, second = $second"
Output:
After swapping, numbers are:
first = 10, second = 5
How to execute the bash files?
Write the bash code into a file and save that file with .sh extension i.e. filename.sh
Open terminal and execute the file using below command:
#make .sh file executable
chmod +x filename.sh
#then run this command
./filename.sh
Contact Us