Introduction
The Linux command line provides powerful tools for performing arithmetic calculations. One of the most versatile calculators available in Linux is bc (Basic Calculator), which allows users to perform both simple and complex mathematical operations directly from the terminal.
In this lab, you will learn how to use the bc command to perform various arithmetic calculations in Linux. You will start with basic operations and progressively move to more complex expressions. The skills you learn will be useful for scripting, data processing, and solving computational problems efficiently in a Linux environment.
By the end of this lab, you will be able to:
- Perform basic arithmetic operations using
bc - Handle complex mathematical expressions with multiple operations
- Use variables and control precision in calculations
- Create scripts that automate mathematical computations
Let's begin exploring the capabilities of the Linux bc calculator.
Basic Arithmetic with bc
In this step, we will learn how to use the bc command for basic arithmetic operations in Linux. The bc command is a powerful calculator tool that allows you to perform calculations directly from the terminal.
Installing bc
First, let's ensure that the bc calculator is installed on your system:
sudo apt-get update
sudo apt-get install -y bc
You should see output indicating the installation process. Once installed, you can verify it's working by typing:
bc --version
You should see version information for the bc calculator.
Creating a Simple Addition Script
Now, let's create a simple script to perform an addition operation using bc:
- Navigate to the project directory:
cd ~/project
- Create a new script file named
simple_calc.sh:
touch simple_calc.sh
- Open the file with nano editor:
nano simple_calc.sh
- Add the following content to the file:
#!/bin/zsh
## Simple addition using bc
echo "20 + 5" | bc
Save the file by pressing
Ctrl+O, thenEnter, and exit nano withCtrl+X.Make the script executable:
chmod +x simple_calc.sh
- Run the script:
./simple_calc.sh
You should see the output:
25
This demonstrates how bc takes the expression "20 + 5" as input and produces the result 25.
Understanding how bc works
The bc command is a pipeline-oriented calculator. We use the pipe symbol (|) to send expressions to bc for evaluation. The basic syntax is:
echo "expression" | bc
You can also try other basic operations:
echo "10 - 3" | bc ## Subtraction
echo "4 * 6" | bc ## Multiplication
echo "15 / 3" | bc ## Division
Run these commands in your terminal to see the results:
echo "10 - 3" | bc
echo "4 * 6" | bc
echo "15 / 3" | bc
The output should be:
7
24
5
Floating-Point Calculations with bc
In this step, we will learn how to perform floating-point calculations using the bc calculator. By default, bc performs integer arithmetic, but we can use the scale parameter to control decimal precision.
Understanding the scale Parameter
The scale parameter in bc determines the number of decimal places to be used in calculations. Let's see how it works:
- Try this command to perform division without setting the scale:
echo "5 / 2" | bc
The output will be:
2
Notice that the result is truncated to an integer, not rounded.
- Now, let's set a scale to get a more precise result:
echo "scale=2; 5 / 2" | bc
The output will be:
2.50
The scale=2 tells bc to calculate the result with 2 decimal places.
Creating a Script for Complex Calculations
Let's create a script that demonstrates using scale and performs more complex calculations:
- Navigate to the project directory if you're not already there:
cd ~/project
- Create a new script file named
complex_calc.sh:
touch complex_calc.sh
- Open the file with nano editor:
nano complex_calc.sh
- Add the following content to the file:
#!/bin/zsh
## Complex calculation using bc with scale
result=$(echo "scale=2; (10.5 * 4.2) - (5.5 / 2) + 3^2" | bc)
echo "Result: $result"
This script:
- Sets the scale to 2 decimal places
- Performs multiplication: 10.5 * 4.2
- Performs division: 5.5 / 2
- Calculates a power: 3^2 (3 raised to the power of 2)
- Combines these operations with addition and subtraction
- Stores the result in a variable named
result - Prints the result with a descriptive label
Save the file by pressing
Ctrl+O, thenEnter, and exit nano withCtrl+X.Make the script executable:
chmod +x complex_calc.sh
- Run the script:
./complex_calc.sh
You should see output similar to:
Result: 46.35
Let's break down the calculation:
- 10.5 * 4.2 = 44.1
- 5.5 / 2 = 2.75
- 3^2 = 9
- 44.1 - 2.75 + 9 = 50.35
Wait, the expected result should be 50.35, but we got 46.35. This is because the calculation in the script needs to be corrected. Let's fix it:
nano complex_calc.sh
Update the calculation:
#!/bin/zsh
## Complex calculation using bc with scale
result=$(echo "scale=2; (10.5 * 4.2) - (5.5 / 2) + 3^2" | bc)
echo "Result: $result"
## Breaking down the calculation
part1=$(echo "scale=2; 10.5 * 4.2" | bc)
part2=$(echo "scale=2; 5.5 / 2" | bc)
part3=$(echo "3^2" | bc)
echo "Part 1 (10.5 * 4.2): $part1"
echo "Part 2 (5.5 / 2): $part2"
echo "Part 3 (3^2): $part3"
echo "Final: $part1 - $part2 + $part3 = $(echo "scale=2; $part1 - $part2 + $part3" | bc)"
Save the changes and run the script again:
./complex_calc.sh
This updated script will show the breakdown of each part of the calculation, making it easier to understand how the final result is obtained.
Working with Variables in bc
In this step, we will learn how to use variables within bc to make our calculations more flexible and powerful. The bc calculator allows us to define variables and reuse them in multiple calculations.
Using Variables in bc Interactively
First, let's explore how to use variables directly in the bc interactive mode:
- Start the
bccalculator in interactive mode:
bc
- Define a variable and perform calculations with it:
x = 10
x + 5
x * 2
You should see:
15
20
- You can define multiple variables and use them together:
y = 7
x + y
x * y
The output will be:
17
70
- Exit the interactive mode by pressing
Ctrl+Dor typingquit.
Creating a Script with bc Variables
Now, let's create a script that demonstrates using variables in bc calculations:
- Navigate to the project directory if you're not already there:
cd ~/project
- Create a new script file named
variable_calc.sh:
touch variable_calc.sh
- Open the file with nano editor:
nano variable_calc.sh
- Add the following content to the file:
#!/bin/zsh
## Script to demonstrate using variables in bc
## Define input values
radius=5
height=10
## Calculate cylinder volume (π * r² * h)
volume=$(echo "scale=2; 3.14159 * $radius * $radius * $height" | bc)
## Calculate cylinder surface area (2π * r² + 2π * r * h)
surface_area=$(echo "scale=2; 2 * 3.14159 * $radius * $radius + 2 * 3.14159 * $radius * $height" | bc)
## Display results
echo "Cylinder properties with radius $radius and height $height:"
echo "Volume: $volume cubic units"
echo "Surface Area: $surface_area square units"
This script:
- Defines variables for the radius and height of a cylinder
- Calculates the volume using the formula π r² h
- Calculates the surface area using the formula 2π r² + 2π r * h
- Displays the results with appropriate units
Save the file by pressing
Ctrl+O, thenEnter, and exit nano withCtrl+X.Make the script executable:
chmod +x variable_calc.sh
- Run the script:
./variable_calc.sh
You should see output similar to:
Cylinder properties with radius 5 and height 10:
Volume: 785.39 cubic units
Surface Area: 471.23 square units
Using Variables Inside bc
We can also define and use variables entirely within bc using a multi-line approach. Let's create another script to demonstrate this:
- Create a new file:
nano bc_variables.sh
- Add the following content:
#!/bin/zsh
## Script to demonstrate using variables within bc
bc << EOF
scale=2
radius = 5
height = 10
pi = 3.14159
## Calculate cylinder volume
volume = pi * radius^2 * height
print "Volume: ", volume, " cubic units\n"
## Calculate cylinder surface area
surface_area = 2 * pi * radius^2 + 2 * pi * radius * height
print "Surface Area: ", surface_area, " square units\n"
EOF
This script:
- Uses a "here document" (EOF) to send multiple lines to
bc - Defines all variables within
bcitself - Performs calculations using these variables
- Uses the
printcommand inbcto display results
- Save the file, make it executable, and run it:
chmod +x bc_variables.sh
./bc_variables.sh
The output should be similar to the previous script but demonstrates a different approach to using variables with bc.
Creating a Practical bc Calculator Script
In this final step, we will create a more practical calculator script that brings together all the concepts we've learned. This script will allow users to perform various calculations by selecting options from a menu.
Building an Interactive Calculator
Let's create a script that functions as an interactive calculator:
- Navigate to the project directory if you're not already there:
cd ~/project
- Create a new script file named
calculator.sh:
touch calculator.sh
- Open the file with nano editor:
nano calculator.sh
- Add the following content to the file:
#!/bin/zsh
## Interactive calculator script using bc
## Function to calculate area of a circle
calculate_circle_area() {
echo -n "Enter the radius of the circle: "
read radius
area=$(echo "scale=2; 3.14159 * $radius * $radius" | bc)
echo "The area of the circle with radius $radius is: $area square units"
}
## Function to calculate area of a rectangle
calculate_rectangle_area() {
echo -n "Enter the length of the rectangle: "
read length
echo -n "Enter the width of the rectangle: "
read width
area=$(echo "scale=2; $length * $width" | bc)
echo "The area of the rectangle with length $length and width $width is: $area square units"
}
## Function to solve quadratic equation ax² + bx + c = 0
solve_quadratic() {
echo -n "Enter coefficient a: "
read a
echo -n "Enter coefficient b: "
read b
echo -n "Enter coefficient c: "
read c
## Calculate discriminant
discriminant=$(echo "scale=4; ($b * $b) - (4 * $a * $c)" | bc)
## Check the discriminant
if (($(echo "$discriminant < 0" | bc -l))); then
echo "The equation has no real solutions (discriminant < 0)"
elif (($(echo "$discriminant == 0" | bc -l))); then
## One solution
x=$(echo "scale=4; -$b / (2 * $a)" | bc)
echo "The equation has one solution: x = $x"
else
## Two solutions
x1=$(echo "scale=4; (-$b + sqrt($discriminant)) / (2 * $a)" | bc -l)
x2=$(echo "scale=4; (-$b - sqrt($discriminant)) / (2 * $a)" | bc -l)
echo "The equation has two solutions:"
echo "x1 = $x1"
echo "x2 = $x2"
fi
}
## Main program loop
while true; do
echo ""
echo "===== BC Calculator Menu ====="
echo "1. Calculate area of a circle"
echo "2. Calculate area of a rectangle"
echo "3. Solve quadratic equation (ax² + bx + c = 0)"
echo "4. Exit"
echo ""
echo -n "Enter your choice (1-4): "
read choice
case $choice in
1) calculate_circle_area ;;
2) calculate_rectangle_area ;;
3) solve_quadratic ;;
4)
echo "Exiting calculator. Goodbye!"
exit 0
;;
*) echo "Invalid option. Please try again." ;;
esac
done
This script:
- Defines functions for different types of calculations
- Provides a menu interface for the user to select the desired calculation
- Uses
bcfor all mathematical operations - Handles more complex mathematical formulas like the quadratic equation
Save the file by pressing
Ctrl+O, thenEnter, and exit nano withCtrl+X.Make the script executable:
chmod +x calculator.sh
- Run the calculator script:
./calculator.sh
- Try each option in the menu:
- Choose option 1 and enter a radius to calculate the area of a circle
- Choose option 2 and enter length and width to calculate the area of a rectangle
- Choose option 3 and enter coefficients to solve a quadratic equation (try a=1, b=5, c=6)
- Choose option 4 to exit the calculator
For example, if you choose option 3 and enter a=1, b=5, c=6, you should see output similar to:
The equation has two solutions:
x1 = -2.0000
x2 = -3.0000
This interactive script demonstrates how bc can be incorporated into more complex programs to solve a variety of mathematical problems.
Summary
In this lab, you have learned how to use the bc command-line calculator in Linux to perform various arithmetic operations.
Here is a summary of what you have accomplished:
Basic Arithmetic Operations:
- Installed and verified the
bccalculator - Created a simple script to perform addition
- Learned how to use the pipe operator to send expressions to
bc - Practiced basic operations like addition, subtraction, multiplication, and division
- Installed and verified the
Floating-Point Calculations:
- Used the
scaleparameter to control decimal precision - Created a script for more complex calculations involving multiple operations
- Understood order of operations and how to use parentheses to control calculation flow
- Used the
Working with Variables:
- Used shell variables with
bccalculations - Explored the interactive mode of
bcfor defining and using variables - Created scripts that utilize variables for more flexible calculations
- Learned how to use "here documents" for multi-line
bcoperations
- Used shell variables with
Practical Applications:
- Built an interactive calculator script with a menu interface
- Implemented common geometric calculations
- Solved more complex equations like quadratic formulas
- Combined all the learned concepts into a useful application
These skills enable you to perform mathematical operations efficiently in the Linux command line and to automate calculations in your scripts. The bc calculator is a powerful tool that can handle everything from simple arithmetic to complex mathematical formulas, making it an essential utility for system administrators, developers, and data analysts working in a Linux environment.
As you continue to work with Linux, you will find that combining command-line tools like bc with shell scripting can help you solve a wide range of problems more efficiently.



