Logo

The Linux bc Command with 9 Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

bc command in linux

In the world of Linux, efficiency and precision are key traits of the popular commands and utilities. 

The bc (Basic Calculator) command is case in point.

This is a versatile tool that provides extensive arithmetic capabilities from the command line. Ideal for both simple calculations and complex mathematical operations, bc becomes indispensable for developers, system administrators, and anyone who needs quick calculations or to automate math tasks in scripts.

In this tutorial, we will go into the details of the bc command, including the syntax and options. Next, we will take a close look at nine examples that demonstrate the capabilities of this command. 

Table Of Contents

  1. The Prerequisites
  2. An Overview of the bc Command
    1. Install the bc Command
    2. The Linux bc Command Syntax
    3. The Linux bc Command Options
  3. How does Linux bc Command Work?
    1. Linux bc Command as an Interactive Mathematical Shell
    2. Linux bc Command as a Mathematical Script Language
  4. Conclusion
  5. FAQs

The Prerequisites

Before diving into the bc command, ensure you have the following:

  • A system running a stable version of a mainstream Linux distribution 
  • You have the bc command installed on your system

An Overview of the bc Command

The bc command is an important go-to option when you need to run quick calculations during script execution. 

Let’s start with how you can install the command on your system.

Install the bc Command

Most Linux distributions have the bc command pre-installed. 

You can easily check if this is the case with your system by typing bc in the terminal.

The command launches the bc calculator if it is present.

If not, you can install it using your distribution’s package manager.

For Debian-based distributions like Ubuntu:

# sudo apt-get install bc

For RHEL-based distributions like CentOS:

# sudo yum install bc

The Linux bc Command Syntax

The basic syntax of the bc command is:

# bc [options] [file...]

Here, 

[options] are command-line flags that modify the behavior of bc.

[file…] represents optional script files you can execute using bc. These files can contain mathematical expressions that the command executes for automated calculations. 

If a file is not specified, the system enters interactive mode, prompting the user for input.

The Linux bc Command Options

bc offers several options that tailor its default functionality. The most common options are:

options of bc command in linux

How does Linux bc Command Work?

The bc command processes expressions from files specified at the command line in the order listed. Once the files are processed, bc starts reading from the standard input, executing expressions as it is read. 

The bc command can be used in two primary modes: an interactive mathematical shell and a processor for mathematical scripts.

In interactive mathematical shell mode, bc acts like a standard calculator, allowing you to enter expressions and get results in real time. Users can enter mathematical expressions directly into the terminal where bc evaluates them.

In script mode, bc can execute a series of expressions from a file or standard input, making it a powerful option for complex calculations that require logic and variable storage.

bc offers users the flexibility to specify input and output bases for mathematical operations, including decimal, octal, or hexadecimal values. In addition, users can manipulate variables or convert values. By default, the base value is decimal, and a scaling option for decimal point notation is provided.

The bc command supports a wide range of standard expressions, including:

  • Arithmetic operators.
  • Increment and decrement operations.
  • Assignment operators.
  • Comparison and relational operations.
  • Logical and boolean operations.
  • Math functions.
  • Conditional statements.
  • Iterative statements.
  • C-like comments that begin with /* and end with */.

Some fundamental and specialized expressions supported by bc include:

function of bc command in linux

For a complete list of supported expressions and functions, refer to the bc command manual.

Linux bc Command as an Interactive Mathematical Shell

Linux bc command is an interactive mathematical shell that offers advanced mathematical functions and supports floating-point number comparisons. 

Let’s see some of the most common applications of this mode.

Example #1: Use bc as a Calculator

Type bc in your terminal to start it in interactive mode.

To exit the shell, type Ctrl+D or quit.

Use bc as a Calculator

The bc command serves as a versatile CLI-based calculator, offering capabilities for basic arithmetic operations like addition, subtraction, division, and multiplication, as well as advanced mathematical functions such as sine, cosine, tangent, and natural logarithms.

For instance, run the following command to try a basic addition operation:

# bc
1+1

The command displays:

2

2

Next, try a multiplication problem:

# bc
4*6

The output displays:

24

24

Example #2: Work with Floating-point (Decimal Numbers)

By default, bc operates with integers and does not handle floating-point numbers, unless specified. Use the -l option to enable the mathematical library, allowing decimal number calculations.

When working with these numbers, bc defaults to zero places after the decimal point. You can adjust the scale value to determine the number of decimal places in the output. 

For instance, by setting the scale variable to 3, the program retains three decimal places.

You can try this idea by running the following commands:

# bc -l
scale=3
22/7

You will see the following output:

3.142

3.142

Example #3: Pipe Input from echo

You can pipe echo command output into bc for quick calculations without entering the interactive shell.

For instance, run the following command:

# echo "scale=2; 10/3" | bc

Here,

echo displays the provided text on the terminal.

pipe (|) redirects the output of the preceding command (echo) as input to the bc command. This input consists of setting the scale to 2 and the expression to 10/3.

The output produced would be:

3.33

3.33

Example #4: Convert Decimal to Hexadecimal

In addition to the arithmetic operations, you can utilize bc to seamlessly convert values between different number systems (decimal, hexadecimal, binary, etc.). 

This functionality is facilitated through two key variables – ibase (input base) and obase (output base). These variables determine the conversion base for both input and output numbers. Valid obase values span from 2 to 999, while valid ibase values range from 2 to 16.

For instance, consider the following command, which converts 255 from base 10 to base 16:

# bc
obase=16
255

The output results in:

FF

Alternatively, you can use the echo command and pipe the expression into bc. The syntax, in this case, will be as follows:

FF

Example #5: Convert Decimal to Binary

Using – ibase and obase, bc allows users to convert decimals to binary numbers.

To convert decimal to binary, set the obase variable to 2, indicating binary output.

For instance, to convert the number 12 to binary, you can opt for one of the following options:

# bc
obase=2
12

Or

# echo 'obase=2;12' | bc

The output results in:

1100

1100

Both methods achieve the same result: converting the decimal number 12 to its binary equivalent, which is 1100.

Linux bc Command as a Mathematical Script Language

The bc command bypasses most of the constraints of shell scripting languages, which are typically confined to integer arithmetic. As a result, it’s commonly integrated into pre-existing shell scripts using a pipe.

Example #1: Declare Variables

Unlike some languages, bc doesn’t require a formal variable declaration. You can simply assign a value to a name, and it becomes a variable. Once assigned, you can use the variable name in subsequent calculations.

For instance, consider the following sequence of commands:

# bc
x=5
x*3

The output would be:

15

15

Example #2: Specify Input Files

You can use bc with files to iterate complex calculations multiple times. 

This requires you to supply input from one or more files by simply specifying the file path(s) when executing the bc command. It is important that these files must be in text format and readable by bc. The command supports the processing of multiple files simultaneously.

Run the following commands in the terminal:

# echo "x=5; x+1" > calc.txt

# bc calc.txt

The first command redirects the expressions to a file named calc.txt. The second command invokes the bc command and passes the file to it as an argument. 

The output results in:

6

output 6

Alternatively, you can create the file using the echo command. Next, you can pipe it to bc.

Consider the following screenshot that demonstrates this process:

6

Example #3: Create An Interactive Script

You can make scripts that add an interactive angle to calculations. 

Let’s make a basic script for converting temperature values from Fahrenheit to Celsius. 

Create a new file and paste the following lines into it:

scale=2

print "\nConvert Fahrenheit degrees to Celsius\n\n"

print "Enter temperature in Fahrenheit: " ; fah = read()

print "\n"

print "The equivalent Temperature in Celsius is: "

(fah - 32.0) * 5.0 / 9.0

Quit

Next, execute the bc command:

# bc -q [file_name]

bc -q

Here,

scale=2: Sets the output to display two decimal places.

print statements: Present informative messages to the user.

read(): Prompts the user to enter the Fahrenheit temperature value and stores it in the variable fah.

Example #4: Using the if Statements

The bc command supports a variety of control statements, such as the if/else statement structure. 

Unlike conventional if/else statements you could find in programming languages, the else clause is enclosed in braces, while the then clause is not. Note that both clauses are terminated with a semicolon.

Consider this example that demonstrates if statements in the bc command used in a script. 

Create a script using a text editor and paste the following code:

define f (x) {

                if (x <= 1) return (1);

                return (f(x-1) * x);

              }

Save the file.

Next, run the following command in the terminal:

# bc -q [filename]

Test the script to verify that the code works as intended:

5040

As you can see, the answer correctly shows the factorial of 7 is 5040.

Conclusion

The bc command is a powerful ally in performing both quick calculations and complex mathematical operations directly from your Linux command line. Whether you’re calculating resources for servers or performing daily tasks, bc provides precision and efficiency. 

We highlighted the utility of the bc command by exploring nine practical examples. We recommend trying out these examples and using them to solve the specific challenges you may face in your server management operations. 

FAQs

Q. Can I use bc for floating-point arithmetic?

Yes, by using the -l option, bc supports floating-point arithmetic and more complex mathematical functions.

Q. What is the bc command in Linux?

The bc command is a versatile command-line calculator that comes pre-installed on most Linux distributions. It provides extensive mathematical capabilities, allowing users to perform complex calculations directly from the terminal.

Q. What types of calculations can I perform with bc?

With bc, you can perform a wide range of mathematical operations, including basic arithmetic (addition, subtraction, multiplication, division), exponentiation, trigonometric functions, logarithms, and more. It also supports control structures such as if statements, loops, and functions.

Q. How do I use the bc command?

To use bc, simply open your terminal and type bc followed by any mathematical expression you want to evaluate. You can also pass input from files or through pipes for more complex calculations.

Q. Can bc handle floating-point arithmetic?

Yes, bc can handle floating-point arithmetic, making it suitable for both integer and non-integer calculations. It provides precise decimal arithmetic with configurable precision settings.

Q. Can I perform conversions with bc?

Yes, bc supports conversions between different number bases (binary, octal, decimal, hexadecimal). You can specify input and output bases using the ibase and obase variables, making it useful for tasks like unit conversion or number system conversions.

Q. Is bc suitable for scripting?

Yes, bc can be integrated into shell scripts to perform calculations or automate mathematical tasks. You can use bc within bash scripts by piping input to the bc command or by embedding bc expressions directly into your scripts.

Q. How can I increase precision in bc?

You can adjust the precision of bc‘s calculations by setting the scale variable. The scale determines the number of decimal places in the output. You can change the scale using the scale command or by setting the BC_LINE_LENGTH environment variable.

Q. Are there any limitations to using bc?

While bc is powerful, it’s worth noting that it’s primarily a command-line tool and may not have the graphical interface of some desktop calculators. Additionally, complex calculations may require careful attention to syntax and precision settings.

Q. Can I customize the behavior of bc?

Yes, bc offers various customization options, including setting the default output format, changing the default scale, and defining custom functions. You can modify bc‘s behavior by setting environment variables or using command-line options.

Q. Where can I find more information about bc?

For additional information about bc‘s features, syntax, and usage, refer to the bc manual page (man bc) or consult online resources and tutorials. Additionally, exploring examples and experimenting with bc in your terminal can help you become more proficient with its capabilities.

 

Try this guide with our instant dedicated server for as low as 40 Euros