Introduction
In this lab, you will learn how to perform arithmetic operations in Shell programming using the basic arithmetic operators.
This tutorial is from open-source community. Access the source code
In this lab, you will learn how to perform arithmetic operations in Shell programming using the basic arithmetic operators.
First, let's define the costs of different fruits and the cost of the basket.
Create a new file and save it with ~/project/operators.sh
.
#!/bin/bash
COST_PINEAPPLE=50
COST_BANANA=4
COST_WATERMELON=23
COST_BASKET=1
Next, we will calculate the total cost of a fruit basket, which contains 1 pineapple, 2 bananas, and 3 watermelons.
#!/bin/bash
COST_PINEAPPLE=50
COST_BANANA=4
COST_WATERMELON=23
COST_BASKET=1
## Calculate the total cost
TOTAL=$((COST_PINEAPPLE + (COST_BANANA * 2) + (COST_WATERMELON * 3) + COST_BASKET))
Finally, let's display the total cost of the fruit basket.
#!/bin/bash
COST_PINEAPPLE=50
COST_BANANA=4
COST_WATERMELON=23
COST_BASKET=1
## Calculate the total cost
TOTAL=$((COST_PINEAPPLE + (COST_BANANA * 2) + (COST_WATERMELON * 3) + COST_BASKET))
## Display the total cost
echo "Total Cost is $TOTAL"
cd ~/project
chmod +x operators.sh
./operators.sh
The output will be:
Total Cost is 128
In this lab, you learned how to perform arithmetic operations using the basic arithmetic operators in Shell programming. By defining variables for the costs of various items and using appropriate arithmetic expressions, you were able to calculate the total cost of a fruit basket.