0% found this document useful (0 votes)
62 views

5 Assignment

This Bash script performs arithmetic operations on the digits of a given number based on the last character of the input. It takes a number as input, separates the last character as the operator, performs the operation indicated on each digit of the remaining number, and outputs the result. Supported operators are + for sum, - for subtraction, x for multiplication, and / for division.

Uploaded by

Venkatesh gh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

5 Assignment

This Bash script performs arithmetic operations on the digits of a given number based on the last character of the input. It takes a number as input, separates the last character as the operator, performs the operation indicated on each digit of the remaining number, and outputs the result. Supported operators are + for sum, - for subtraction, x for multiplication, and / for division.

Uploaded by

Venkatesh gh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#!

/bin/bash

<<Documentation
Name: Sadashiv Hegadi
Date: 16-04-2023
Description: Write a script to perform arithmetic operation on digits of a given
number
Sample input: bash operator_dependent.sh 1234+
Sample output: Sum of digits = 10
Documentation

if [ $# -eq 1 ]
then
cla=$1
length=${#cla}
if [ $length -gt 1 ]
then
var=`echo ${cla: -1}`
var2=`echo ${cla: :-1}`
arthmetic=0
length=${#var2}
case $var in
+)for i in `seq 0 $(($length-1))`
do
digit1=`echo "${var2:i:1}"`
arthmetic=`echo "$arthmetic+$digit1" | bc`
done
echo "Sum of digits = $arthmetic";;
-)arthmetic=`echo "${var2:0:1}"`
for i in `seq 1 $(($length-1))`
do
digit1=`echo "${var2:i:1}"`
arthmetic=`echo "$arthmetic-$digit1" | bc`
done
echo "Subtraction of digits = $arthmetic";;
x)arthmetic=`echo "${var2:0:1}"`
for i in `seq 1 $(($length-1))`
do
digit1=`echo "${var2:i:1}"`
arthmetic=`echo "$arthmetic*$digit1" | bc`
done
echo "Multiplication of digits = $arthmetic";;
/)arthmetic=`echo "${var2:0:1}"`
for i in `seq 1 $(($length-1))`
do
digit1=`echo "${var2:i:1}"`
arthmetic=`echo "scale=2;$arthmetic/$digit1" | bc`
done
echo "Division of digits = $arthmetic";;
*)echo "Error: Operator missing or invalid operator, please pass
operator as last digit (+,-,x,/)";;
esac
else
echo "Error : Please pass the arguments through CL.
Usage : ./operator_dependent.sh 2345+"
fi
else
echo "Error : Please pass the arguments through CL."
echo "Usage : ./operator_dependent.sh 2345+"
fi

You might also like