Linux
2) Write a bash script which when executed, expects
two integers, say n1 and n2. If the first argument, n1, is greater
than the second argument, n2, the script calls a function (written
within the script) and passes to the function n1 and n2 to compute
the sum from n1 to n2. This function returns the sum which the
script prints. If n1 is not greater than n2, the script calls the
same function and passes the n1 and n2 to compute the sum from n2
to n1, and the script prints the sum returned by the function.
Below is the expected dialog or interface
$ ./script9
ERROR: The script expects two arguments.
$ ./script9 3 6
The sum from 3 to 6 is 18.
$ ./script9 3 3
The sum from 3 to 3 is 3.
$ ./script9 6 3
The sum from 3 to 6 is 18.
Program:
#!/bin/bash
airth_sum(){
n1=$1
n2=$2
if [ "$n1" -gt "$n2" ];then
sum=$((n1*(n1+1)/2-(n2-1)*n2/2))
elif [ "$n1" -lt "$n2" ];then
sum=$((n2*(n2+1)/2-(n1-1)*n1/2))
else
sum=$n1
fi
echo "$sum" #Whatever is printed is stored in sum_calc variable, by
default shell return will return the status of execution
}
#Condition to evaluate the no of arguments
if [ "$#" -ne 2 ];
then
echo "ERROR: The script expects two arguments."
exit 1;
fi
n1=$1
n2=$2
sum_calc=$(airth_sum $n1 $n2)
if [ "$n1" -lt "$n2" ];then
large_no=$n2
small_no=$n1
else
large_no=$n1
small_no=$n2
fi
echo "The sum from $small_no to $large_no is $sum_calc"
Output:
Get Answers For Free
Most questions answered within 1 hours.