The Wayback Machine - https://web.archive.org/web/20240118181401/https://www.geeksforgeeks.org/simple-calculator-bash/
Open In App
Related Articles

Simple Calculator in Bash

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input in Bash.

Example: 

Enter two numbers:
5.6
3.4
Enter Choice: 
1. Addition
2. Subtraction
3. Multiplication
4. Division
3
5.6 * 3.4 = 19.0 

Approach:  

1. Read Two Numbers
2. Input Choice (1-Addition, 2-Subtraction, 3-Multiplication, 4-Division) 
3. if Choice equals 1
    Calculate res = a + b
   else If Choice equals 2
    Calculate res = a - b
   else if Choice equals 3
    Calculate res = a * b
   else if Choice equals 4
    Calculate res = a / b
4. Output Result, res

Commands/Statement Used: 

1. echo 
echo is one of the mostly used command. 
It is used to print a line of text in standard output.  

$ echo [-neE] [arg ...] 

2. read 
The command read in Linux is used to read the input from the keyboard. 
3. Switch-Case 
When there are a lot of if statement in Shell and it becomes confusing. Then it is good to use case statement.
4. bc Command 
Checkout the link for bc Command bc Command Linux Example

Bash




# !/bin/bash
 
# Take user Input
echo "Enter Two numbers : "
read a
read b
 
# Input type of operation
echo "Enter Choice :"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch
 
# Switch Case to perform
# calculator operations
case $ch in
  1)res=`echo $a + $b | bc`
  ;;
  2)res=`echo $a - $b | bc`
  ;;
  3)res=`echo $a \* $b | bc`
  ;;
  4)res=`echo "scale=2; $a / $b" | bc`
  ;;
esac
echo "Result : $res"


Output:

 

Time Complexity: O(1)
Auxiliary Space: O(1)

References: 
Array Basics Shell Scripting | Set 2 (Using Loops) 
Array Basics in Shell Scripting | Set 1 
Sorting an array in Bash using Bubble sort 
bc Command Linux Example
 

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads