Friday, December 27, 2024
Google search engine
HomeGuest BlogsLinux bc Command with Examples

Linux bc Command with Examples

Introduction

The Linux bc command (short for basic calculator) is a command-line utility that acts as a scientific calculator. The command interprets the bc language and performs arbitrary precision arithmetic with interactive statement execution.

Use the bc command as an interactive mathematical shell that takes standard input or as a mathematical scripting language.

In this tutorial, you will learn to use the bc command in Linux and see practical use-case examples.

Linux bc command explained with examples.Linux bc command explained with examples.

Prerequisites

  • A system running Linux.
  • Access to the terminal (Ctrl+Alt+T).

Linux bc Command Syntax

The bc command has syntax similar to the C programming language. The general command syntax is:

bc [options] [ file ]
  • The available [options] are explained in the section below.
  • Specify a [file] to read its contents and execute the statements as they are read. Not specifying a file opens the interactive mode and waits for input from the user.

Linux bc Command Options

Use the bc command options to customize the operating mode and specify how to process the input.

The available options are:

Option Long form Description
-c / The -c option compiles the [file] parameter without invoking the dc command. The bc command is a preprocessor for dc, calling it automatically unless the -c option is specified. This causes -c to send the output to standard output.
-h --help Prints the command usage and exits.
-i --interactive Forces the interactive mode.
-l --mathlib Defines a library of math functions and sets the scale variable to 20. The default scale value is 0.
-w --warn Gives warnings for extensions to POSIX bc.
-s --standard Process exactly the POSIX bc language.
-q --quiet Starts the command without printing the GNU bc welcome.
-v --version Prints the program version number, copyright, and quits.

How Linux bc Command Works?

The bc command works by processing code from all the files specified in the command line in the order the files are listed. After processing the files, bc starts reading from the standard input, executing all code as it is read. The command does not read from standard input if a file contains a command to halt the processor.

When specifying input files, make sure they are text files that contain a sequence of commands, statements, or function definitions readable and executable by the bc command. The command allows users to define the math library before processing the files using the -l option.

Important: Although bc works with arbitrary precision, the command defaults to zero digits after the decimal point unless the -l flag is specified or the scale variable is set manually. The -l flag sets the scale variable to 20 digits after the decimal point.

When working with input values, bc allows users to specify an input and output base for mathematical operations in decimal, octal, or hexadecimal values. Users can also work with variables or to convert values. The default value is decimal, and a scaling provision for decimal point notation is also available.

The bc command supports most standard expressions like (+), (), (/), (*), (%), (^), as well as:

  • 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 start with /* and end with */.

Some basic and special expressions that bc supports are:

Function Description
length ( expression ) The length function value is the number of significant digits in the expression.
read ( ) The read function reads a number from the standard input, regardless of where the function occurs. Use with caution as it can cause issues by mixing data and program in the standard input.
scale ( expression ) The number of digits after the decimal point in the expression represents the value of the scale function.
sqrt ( expression ) The square root of the expression is the value of the sqrt function.
++ var Increments the variable by one, and the new value is the result of the expression.
var ++ The expression result is the variable value, and the variable is then incremented by one.
-- var Decrements the variable by one and then stores the new variable value.
var -- The result of the expression is the variable value, and the variable is then decremented by one.
( expr ) The parenthesis alters the standard precedence and forces the evaluation of an expression.
var = expr The var variable is assigned the value of the expression.

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

Linux bc Command as an Interactive Mathematical Shell

Enter the interactive mathematical shell by running the bc command without specifying files:

bc
Starting bc in interactive mode.Starting bc in interactive mode.

The command version and copyright information appear. The command enters the interactive mode and waits for input. When finished, exit the interactive shell by pressing Ctrl+D or by running:

quit

Example 1: Use bc as a Calculator

The bc command can act as a CLI-based calculator for simple mathematical operations such as addition, subtraction, division, and multiplication. It also supports various advanced mathematical functions like sine, cosine, tangent, and natural logarithms.

The calculator is superior to Bash as Bash can’t perform some advanced arithmetic operations, like comparing floats.

For example, run the command and test some mathematical operations:

7+3
3*5
Performing basic calculations in CLI.Performing basic calculations in CLI.

The result is displayed under each operation as the user provides the input.

Example 2: Working with Decimals

When working with decimals, the program defaults to zero digits after the decimal point. However, you can customize the behavior if you define the scale variable value or specify the -l option when running the command.

For example, try dividing eight by three without setting the scale variable. Then, try again after setting it to two decimal places:

Comparing the difference in results when setting the scale variableComparing the difference in results when setting the scale variable

First, the program shows no digits after the decimal point, which is the default behavior. After setting the scale variable value to 2, the program keeps two decimal places. The C-style comment in the example above starts with /* and ends with */ and doesn’t disrupt the program.

Set the scale value to the number of decimal places you want to have in the output. Running the bc command with the -l option keeps 20 decimal places:

Running bc with the -l option to increase decimal points kept.Running bc with the -l option to increase decimal points kept.

Example 3: Pipe Input from echo

The bc command allows users to perform mathematical operations without entering the interactive shell. One of the ways to do that is to pipe the echo command output into bc.

For example:

echo "6+17" | bc
Providing input for bc using the echo command.Providing input for bc using the echo command.

The output shows the result without entering the interactive shell.

It is also possible to set the scale variable value using echo:

Setting the scale variable using the echo command.Setting the scale variable using the echo command.

The output shows the result with five decimal points.

Example 4: Convert Decimal to Hexadecimal

Use bc to convert values from one number system to another. The command achieves that using two special variables – ibase (input base) and obase (output base). The variables define the conversion base for input and output numbers. The legitimate obase values range from 2 to 999, while legitimate ibase values range from 2 to 16.

For example, the following command converts 255 from base 10 to base 16:

echo 'obase=16;255' | bc
Converting decimal to hexadecimal using the bc command.Converting decimal to hexadecimal using the bc command.

Example 5: Convert Decimal to Binary

Using – ibase and obase, bc allows users to convert decimals to binary numbers. For example, the following command converts the number 12 from base 10 to base 2:

echo 'obase=2;12' | bc
Converting decimal to binary using the bc command.Converting decimal to binary using the bc command.

The command allows users to convert values between other supported number systems – decimal, hexadecimal, binary, and octal.

Note: When converting from binary to decimal values, make sure to set the output obase value using hexadecimal values. For example, 10 in hexadecimal is 16.

Linux bc Command as a Mathematical Scripting Language

bc helps overcome the limitations of shell scripting languages that are restricted to integer arithmetic. Thus, the command is often embedded into existing shell scripts with a pipe or a here document.

The examples below show some use cases of bc in shell scripting.

Example 1: Declare Variables

Use shell variables with bc to store a value in a variable, which is useful when writing shell scripts.

For example:

VAR=10 ; echo "$VAR^2" | bc
Declaring variables using the echo command and piping the output to bc.Declaring variables using the echo command and piping the output to bc.

Note: Make sure to use double quotes to preserve the value of the $VAR variable. Read our tutorial to learn the difference between single and double quotes.

Example 2: Specify Input Files

Using bc with files allows users to repeat complex calculations multiple times. To provide the input from a file or multiple files, specify the file path when running the bc command. The file must be a text file readable by bc. Multiple files are supported.

For example, the following file contains several lines of simple mathematical operations, as shown in the cat command output:

Viewing a file's contents using the cat command.Viewing a file's contents using the cat command.

Run the following command to feed the file’s contents to bc:

bc -l calculation.txt
Providing an input file for the bc command.Providing an input file for the bc command.

In the above example, the command with the -l option increases the precision of the result.

Alternatively, pipe the cat command output to bc:

cat calculation.txt | bc -l

Example 3: Create an Interactive Script

Create a shell script to reuse an existing calculation. For example, create a simple Fahrenheit to Celsius temperature conversion script by following the steps below:

1. Create a new text file using a text editor and paste the following lines:

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

2. Save the file.

3. Execute the file using the following syntax:

bc -q [filename]
Temperature conversion using the bc command.Temperature conversion using the bc command.

The command first asks for input in Fahrenheit and then converts it to Celsius. The -q option runs the command silently without displaying the program version and copyright information.

Example 4: Using if Statements

The bc language supports numerous control statements, including the if/else statement. The difference from general if/else statements is that the else clause is enclosed in braces, while the then clause isn’t. However, both end with a semicolon.

Follow the steps below to create a script for a factorial function (n!):

1. Create a script using a text editor and paste these lines:

define f (x) {
                if (x <= 1) return (1);
                return (f(x-1) * x);
              }

2. Save the file.

3. Execute the script using the following syntax:

bc -q [filename]

Test if the script works by providing an example:

Running a script using the bc command.Running a script using the bc command.

The command calculates the factorial of 5 as 120 (5*4*3*2*1=120), which means that the script works.

Conclusion

This article explained how the bc command works and provided several use-case examples. The bc command offers many possibilities and facilitates writing automation scripts in Bash.

Next, read our detailed tutorial to learn more about Bash math operations and different commands you can use for arithmetic operations.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments