bc Command in Linux



The bc command is a feature-rich tool for performing arbitrary precision calculations. It's like a command-line calculator that allows you to evaluate mathematical expressions. With this command, you can perform mathematical calculations, including basic arithmetic operations and complex computations.

The bc command can handle both floating-point arithmetic and integers and is ideal for interactive use in the terminal as well as for performing calculations within scripts.

The bc command often starts by processing code from all the files listed on the command line in the order they are listed. After all files have been processed, bc starts reading from the standard input. All code is executed as it is read

In addition, the bc command supports variables, assignment operators, math functions, conditional statements, iterative constructs, and more.

Table of Contents

Here is a comprehensive guide to the options available with the bc command −

Syntax of bc Command

The general for this command is as follows −

bc [options] [file]

If you don't specify a [file], it will open in interactive mode, waiting for input. Under options, you can input short or long options.

bc Command Options

The following table highlights the different options available for the bc command −

Tag Description
--help Display help
-h, --help Print the usage and exit.
file

Represents a file containing calculations or functions to perform.

You can pipe input from standard input (stdin) if you don't specify a file.

i, --interactive

Forces interactive mode.

In interactive mode, you can enter expressions directly and get an immediate result.

-l, --mathlib Defines the standard math library. Useful for more complex mathematical operations.
-w, --warn Gives warnings for extensions to POSIX bc. Helps you avoid non-standard behavior.
-s, --standard Processes exactly the POSIX bc language. Useful when you want strict adherence to the standard.
-q, --quiet

Suppresses the normal GNU bc welcome message.

Keeps the output cleaner.

-v, --version

Prints the version number and copyright information.

Helpful for checking the installed version.

Standard Functions Supported by The bc Command

The following are standard functions that the bc command supports −

Tag Description
length (expression) This function returns the number of significant digits in the given expression
read() Reads a number from the standard input. Be cautious when using this function, as it can mix data and program code from user input. It's best suited for previously written programs that need user input but don't allow program code input.
scale(expression) Specifies the number of digits after the decimal point in the result of the expression.
sqrt(expression) Calculates the square root of the expression. The result will have the same number of decimal places as the expression.
++var Increments the variable var by 1 and sets the new value as the result of the expression.
-var++ The result of the expression is the value of the variable, and the variable is then incremented by one.
var Decrements the variable var by 1 and sets the new value as the result of the expression.
var Similar to the previous function, but the decrement happens after evaluating the expression
(expr) Parentheses alter the standard precedence, allowing you to force the evaluation of an expression.
var = expr The variable var is assigned the value of the expression.

Examples of bc Command in Linux

The following are some basic and complex mathematical computations you can perform with the bc command.

  • Basic Arithmetic
  • Assigning Values to Variable
  • Assignment Operators
  • Pre-increment Equivalent
  • Post-increment Equivalent
  • Pre-decrement Equivalent
  • Post-decrement Equivalent
  • Precision and Scale
  • Relational Operators
  • Mathematical Functions
  • Conditional Statements

Basic Arithmetic

In most Linux distributions, the bc command utility comes pre-installed by default. You can perform simple arithmetic operations with bc command using the following symbols −

  • - for subtraction
  • + for addition
  • / for division
  • * for multiplication
  • ^ for exponent
  • % for modulus

To initiate the bc calculator, simply type bc in your terminal −

bc

You'll enter the interactive mode, where you can perform various calculations line by line as shown −

Basic Arithmetic bc Command 1

To exit, press Ctrl + D or type quit, and then press ENTER.

Alternatively, you can use command substitution and the echo command to carry out calculations without having to enter the bc interactive prompt.

echo '15 + 20' | bc
Basic Arithmetic bc Command 2

This will output 35, which is the result of adding 15 and 20

Assigning Values to Variable

You can assign values to variables with the bc command using the = operator. Variables can hold numeric values or even expressions. For instance −

bc
Assigning Values to Variable bc Command

Assignment Operators

With the bc command, you can use assignment operators to assign values to variables and perform different operations on variables. Here is how you can get started.

Assignment (=) operator: This option assigns a value to a variable.

echo "val = 11; val" | bc
Assignment Operators bc Command 1

Subtraction and assignment (=) operator: This option subtracts a value from a variable.

echo "val = 5; val -= 3; val" | bc
Assignment Operators bc Command 2

Exponentiation and Assignment (^=) Operator: This option raises a variable to a power.

echo "val = 5; val ^= 2; val" | bc

val = 5: This assigns the value 5 to the variable "val."

val ^= 2: The ^= operator calculates the exponentiation (raising to the power) of the variable "val" by 2. In this case, it computes (5^2), which is 25.

Assignment Operators bc Command 3

Division and Assignment (/=) operator: This option divides a variable by a value.

echo "val = 16; val /= 2; val" | bc
Assignment Operators bc Command 4

Pre-increment Equivalent

You can perform the pre-increment equivalent using the following syntax −

echo "var=7; var = var + 1; var" | bc

This command initializes a variable var with the value 7, increments it by 1, and then prints the updated value, which is 8.

Pre-increment Equivalent bc Command

Post-increment Equivalent

You can perform the post-increment equivalent using the following syntax −

echo "var=9; result = var; var = var + 1; result" | bc

This command initializes a variable var with the value 9, assigns it to another variable result, increments var by 1, and then prints the original value of the result, which remains 9.

Post-increment Equivalent bc Command

Pre-decrement Equivalent

This option is the opposite of the pre-increment equivalent. To get started, simply use the following syntax −

echo "var=16; var = var - 1; var" | bc

This command initializes a variable var with the value 16, decrements it by 1, and then prints the updated value, which is 15.

Pre-decrement Equivalent bc Command

Post-decrement Equivalent

You can perform the post-decrement equivalent using the following syntax −

echo "var=10; result = var; var = var - 1; result" | bc

This command initializes a variable var with the value 10, assigns it to another variable result, decrements var by 1, and then prints the original value of the result, which remains 10.

Post-decrement Equivalent bc Command

Precision and Scale

By default, the bc command uses a scale of 0, which results in integer arithmetic. If you want to perform floating-point calculations with a specific level of precision, you can adjust the scale. For instance −

bc
scale=2
14 / 3

In the above example, we've set the scale to 2, showing that we want two decimal places in the result. As a result, bc conducts floating-point division, and the result is 4.66.

Precision and Scale bc Command

Relational Operators

Relational operators allow you to compare values and determine whether a certain condition is true or false. Here's how you can use these relational operators −

Not Equal To (!=) Operator

This option returns the value of a (left operand) if it is not equal to the value of b (right operand); otherwise, it returns 0.

echo "1 != 5" | bc
Relational Operators bc Command 1

Equality (==) Operator

This option returns 1 if the value of the left operand is equal to the right operand, otherwise 0.

echo "4 == 4" | bc
Relational Operators bc Command 2

Less Than (<) Operator

This option returns 1 if the value of the left operand is less than the right operand, otherwise 0.

echo "8 < 5" | bc
Relational Operators bc Command 3

Greater Than (>) Operator

This option returns 1 if the value of the left operand is greater than the right operand, otherwise 0.

echo "7 > 5" | bc
Relational Operators bc Command 4

Mathematical Functions

When you run bc with the "-l" option (which stands for "load"), it preloads a math library. This library provides additional mathematical functions that you can use in your calculations.

Without the "-l" option, bc doesn't load this library, and you won't have access to those extra functions.

The "scale" in bc refers to the number of decimal places used for calculations. By default, bc sets the scale to 0 (integer arithmetic).

However, when you run it with the "-l" flag, it configures the scale to a default value (usually 20). This means that calculations involving decimals will be precise up to 20 decimal places. The following are examples of math functions you perform using this setting.

Square root function (sqrt())

echo "sqrt(9)" | bc
Mathematical Functions bc Command 1

ibase and obase (Number Bases)

echo "ibase=4;1111" | bc -l
echo "obase=6;10" | bc -l
echo "obase=4;ibase=2;101" | bc
Mathematical Functions bc Command 2

Conditional Statements

You can use the bc command to construct conditional statements. To get started, use the following syntax −

if (condition) {statement} else {statement}

For instance −

echo 'a=6;b=8;if(a==b) print "a equals to b" else print "a not equals to b" ' | bc -l
Conditional Statements bc Command

Conclusion

Whether you're new to using the 'bc' command in Linux or aiming to enhance your expertise, we hope you find this guide helpful. By mastering 'bc' and understanding its role in the Linux ecosystem, you'll become a more proficient Linux user.

Advertisements