Arithmetic Operations in Shell Programming

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to perform arithmetic operations in Shell programming using the basic arithmetic operators.

Define variable costs

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

Calculate the total cost

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))

Display the total cost

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

Summary

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.

Other Shell Tutorials you may like