In this article, we’ll learn how to write a Shell Script to exchange the values of two variables using a temporary variable.
#!/bin/bash
# Define two variables
var1="Hello"
var2="World"
echo "Before swapping:"
echo "var1 = $var1"
echo "var2 = $var2"
# Exchange the values of the variables
temp=$var1
var1=$var2
var2=$temp
echo "After swapping:"
echo "var1 = $var1"
echo "var2 = $var2"
In this script, we define two variables var1
and var2
with the values “Hello” and “World” respectively. We then print out the values of the variables before swapping them.
To exchange the values of the variables, we use a temporary variable called temp
. We assign the value of var1
to temp
, then assign the value of var2
to var1
, and finally assign the value of temp
to var2
.
We then print out the values of the variables after swapping them to confirm that the script works as expected.
To run this script, save it in a file with a .sh
extension (e.g. swap.sh
), make the file executable with chmod +x swap.sh
, and then run the script with ./swap.sh
.