Bash bc command in Linux [with Examples]

Last updated: December 6, 2023 | Linuxopsys

The bc (basic calculator) command is used for mathematical calculations, including basic arithmetic operations and high-precision computations. It can handle both integer and floating-point arithmetic and is suitable for interactive use in the terminal as well as for performing calculations within scripts.

Additionally, bc supports variables, assignment operators, mathematical functions, control structures, and more. When compared with expr, bc is a more feature-rich and precise calculator.

Basic Usage

To start the bc calculator, simply type bc in your terminal:

bc
run bc command on terminal

You'll enter the interactive mode, where you can perform calculations line by line. To exit, press Ctrl + D or type quit then press ENTER.

In the majority of Linux distributions, the bc package is installed by default.

If you get the 'bc: command not found' error message, then you have to proceed with the bc package installation on the server.

###Debian/Ubuntu
sudo apt install bc
###RHEL/CentOS Stream
sudo yum install bc
###Fedora
sudo dnf install bc

Performing Basic Arithmetic

You can perform basic arithmetic operations with bc using the following symbols:

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

Example:

$ bc
3 + 5
8
20 * 4
80
10 / 2
5
15 % 7
1

You can also perform calculations without entering the bc interactive prompt by using command substitution and the echo command. This method is particularly useful when you want to calculate a specific expression within a script or as part of a command pipeline.

Example:

$ echo "10.5+5" | bc
5.5

Precision and Scale

By default, bc uses a scale of 0, which means it performs integer arithmetic. You can adjust the scale to specify the desired level of precision for floating-point calculations.

Default Behavior (Scale 0 - Integer Arithmetic):

$ bc
10 / 3
3

In the example above, the result is 3 because it operates with a scale of 0 by default, effectively performing integer division.

Adjusting the Scale (Floating-Point Arithmetic):

$ bc
scale=2
10 / 3
3.33

Here, we set the scale to 2, indicating that we want two decimal places in the result. As a result, bc performs floating-point division, and the result is 3.33.

Assigning Values to Variable

You can assign values to variables in bc using the = operator. Variables can hold numeric values or even expressions.

Example:

$ bc
x = 5
y = 3
x + y
8
result = x * y
result
15

Assignment operators

In bc, you can use assignment operators to assign values to variables and perform various operations on variables. Let's look into some examples:

Assignment (=) operator: Assigns a value to a variable.

$ echo "val = 10; val" | bc
10

Addition and Assignment (+=) operator: Adds a value to a variable and assigns the result back to the variable.

$ echo "val = 5; val += 2; val" | bc
7

Subtraction and Assignment (-=) operator: Subtracts a value from a variable and assigns the result back to the variable.

$ echo "val = 10; val -= 3; val" | bc
7

Division and Assignment (/=) operator: Divides a variable by a value and assigns the result back to the variable.

$ echo "val = 10; val /= 2; val" | bc
5

Exponentiation and Assignment (^=) operator: Raises a variable to a power and assigns the result back to the variable.

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

Modulus and Assignment (%=) operator: Calculates the modulus of a variable and a value and assigns the result back to the variable.

$ echo "val = 10; val %= 3; val" | bc
1

Using increment (++) and decrement (--) operators like other programming languages but aren't directly supported. You typically use assignment statements to perform such operations. Let's look into a few examples.

Pre-increment equivalent in bc:

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

In this example, we first assign a value to var, then increment it by 1 before printing the result.

Post-increment equivalent in bc:

$ echo "var=5; result = var; var = var + 1; result" | bc
5

Here, we first assign var to result, then increment var by 1, and finally print result.

Pre-decrement equivalent in bc:

$ echo "var=15; var = var - 1; var" | bc
14

Similarly, we subtract 1 from var to achieve the pre-decrement operation.

Post-decrement equivalent in bc:

$ echo "var=15; result = var; var = var - 1; result" | bc
15

In this case, we first assign var to result, then decrement var by 1, and finally print result.

Relational Operators

In bc, you can use relational operators to compare two numbers or variables, and the result will be either 1 (true) or 0 (false). Here's how these relational operators work with examples:

Less Than (<) Operator: Returns 1 if the left operand is less than the right operand, otherwise 0.

$ echo "10 < 5" | bc
0

Less Than or Equal To (<=) Operator: Returns 1 if the left operand is less than or equal to the right operand, otherwise 0.

$ echo "10 <= 10" | bc
1

Greater Than (>) Operator: Returns 1 if the left operand is greater than the right operand, otherwise 0.

$ echo "10 > 5" | bc
1

Greater Than or Equal To (>=) Operator: Returns 1 if the left operand is greater than or equal to the right operand, otherwise 0.

$ echo "5 >= 10" | bc
0

Equality (==) Operator: Returns 1 if the left operand is equal to the right operand, otherwise 0.

$ echo "5 == 5" | bc
1

Inequality (!=) Operator: Returns 1 if the left operand is not equal to the right operand, otherwise 0.

$ echo "1 != 2" | bc
1

Logical or Boolean operators

You can use logical or boolean operators to evaluate logical expressions. Here's how these operators work with examples:

Logical AND (&&) Operator: Returns 1 if both expressions are non-zero, otherwise 0.

$ echo "26 && 8" | bc
1

In this example, both 26 and 8 are non-zero, so the result is 1.

Logical OR (||) Operator: Returns 1 if either expression is non-zero, otherwise 0.

$ echo "0 || 0" | bc
0

In this example, neither 0 nor 0 are non-zero, so the result is 0.

Logical NOT (!) Operator: Returns 1 if the expression is zero, otherwise 0.

$ echo "! 0" | bc
1

Here, 0 is zero, so the logical NOT operator ! returns 1.

Mathematical Functions

A math library is preloaded and the default scale has been configured if bc is run with the -l option. The scale set at the time of its call is used by the math functions to calculate their results.

Here are some of the commonly used mathematical functions:

  • s(x): Calculates the sine of x, expressed in radians.
  • c(x): Calculates the cosine of x, expressed in radians.
  • l(x): Computes the natural logarithm (base 'e') of x.
  • e(x): Calculates the exponential function, raising 'e' to the power of x.
  • J(n,x): Computes the integer order n Bessel function of x.

Additional Functions:

  • length(x): Returns the total number of significant decimal digits in the expression x.
  • read(): Reads the input value.
  • scale(expression): Sets the scale (number of decimal digits after the decimal point) based on the expression.
  • sqrt(): Computes the square root of a number.
  • ibase and obase: Specifies the number base for input and output conversion. Base 10 is the default for both input and output.

Some Examples:

Sine and Cosine Functions:

$ echo "s($pi/6)" | bc -l
0.49999999999999999999

$ echo "c($pi/4)" | bc -l
0.70710678118654752440

Length Function (length(x)):

$ echo "length($pi)" | bc -l
21

Square Root Function (sqrt()):

$ echo "sqrt(4)" | bc
2

ibase and obase (Number Bases):

$ echo "ibase=2;1111" | bc -l
15

$ echo "obase=8;10" | bc -l
12

$ echo "obase=8;ibase=2;101" | bc
5

Setting Pi Using a(1):

$ pi=`echo "h=10;4*a(1)" | bc -l`
$ echo $pi
3.14159265358979323844

File Input/Output

You can perform file input and output operations to read input from files and write results to files.

Reading Input from a File:

$ cat inputfile.txt
3 + 5
20 * 4
10 / 2
15 % 7

You can use bc to read and process these expressions from the file as follows:

$ bc < inputfile.txt
8
80
5
1

You can use the > operator to redirect the output to a file.

$ bc < inputfile.txt > outputfile.txt

To append the output to an existing file instead of overwriting it

$ bc < inputfile.txt >> existingfile.txt

Control Structures

Conditional Statements

In bc, you can use conditional statements to make decisions and execute statements based on the evaluation of a condition. The syntax for a conditional statement in bc is as follows:

Syntax:

if(condition) {statement} else {statement}

Here's an example of a conditional statement in bc:

$ echo 'a=8;b=10;if(a==b) print "a equals to b" else print "a not equals to b" ' | bc -l
a not equals to b

Loops

In bc, you can use loop statements to repeat a series of instructions or statements for a certain number of times or until a specific condition is met. The two common types of loop statements in bc are the for loop and the while loop. Here's how they work with examples:

For Loop Syntax:

for (initialization; condition; increment) { statements }

Example

$ echo "for (i = 1; i <= 5; i++) { i; }" | bc
1
2
3
4
5

Whereas the while loop syntax is:

while (condition) { statements }

Example

$ echo "i=0;while(i<5) {i; i+=1}" | bc
0
1
2
3
4

The above command executes a while loop in the bc calculator, which increments the value of the variable i from 0 to 4.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment