Q. How do I swap two numbers using addition and subtraction in Bash
Ans:
#!/bin/bash echo "enter first number" read a echo "enter second number" read b echo "a before swapping is $a and b is $b" #swapping a=$((a+b)) b=$((a - b)) a=$((a-b)) echo "a after swapping is $a and b is $b"
Output
Enjoy :)
If You Liked This Post Please Take a Time To Share This Post
Even simpler and without third variable
ReplyDelete#!/bin/bash
echo "enter first number"
read a
echo "enter second number"
read b
echo "a before swapping is $a and b is $b"
#swapping
read a b <<<"$b $a"
echo "a after swapping is $a and b is $b"
nice :)
Deleteecho "enter the value in var1"
Deleteread n
echo "entered numbr in var 1 is $n"
echo "enter the value in var2"
read m
echo "entered num in var 2 is $m"
echo "b4 swapping the values in var1 and var2 are $n and $m"
var1=$m
var2=$n
echo "aftr swapping the values in var1 and var2 are $m and $n"