Bash bc command in Linux – Usage + Examples

Have you wondered how to perform calculations in Linux and Unix systems? This mostly comes into use when you do programming.

In this tutorial, we learn about bc command in Linux with examples.

bash bc command

The bc command stands for the basic calculator. But also referenced as a bench calculator. It is used to perform basic mathematical calculations.

bc is commonly used in scripting and as well as in the interactive shell.

The most basic elements of bc are numbers. This command line calculator can handle the number of digits before the decimal and the number of digits after the decimal point. The second element is variables that can store numbers. That could be a simple variable or an array. bc also supports functions to perform standard mathematical operations.

Syntax

The basic syntax of bc command:

bc [ -hlwsqv ] [long-options] [ file ... ] 

Install bc in Linux

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

bc command Operations

bc command line calculator can perform arithmetic, Increment/decrement, assignment, logical or boolean, functions, statements, and store variables.

Let’s look into them with examples.

1. Arithmetic Operators

A mathematical function known as an arithmetic operator conducts a calculation on two operands. They are used in everyday math, and the majority of programming languages have a collection of them that may be utilized inside equations to carry out various kinds of sequential calculations.

Examples:

Addition

$ echo "10.5+5" | bc
5.5

We can use the following operators

(+) addition

(-) subtraction

(*) multiplication

(/) division

(%) Modulus

(^) exponent

A sample bash script

#! /bin/bash
echo "10+5" | bc
echo "scale=2;15.5/5" |bc

Where the scale function defines the number of decimal points you want.

2. Increment and decrement operators

Bash supports both the increment and decrement operators, just like other programming languages. By using the increment operator ++, a variable’s value is raised by one. Similarly, the decrement operator — reduces a variable’s value by one.

Pre-increment operator: ++var. Prior to using the variable’s outcome, the variable is first incremented.

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

Post increment operator: var++ . The variable is initially used to provide a result before being increased.

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

Pre-decrement operator: –var. Prior to using the variable’s outcome, the variable is first decreased.

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

Post-decrement operator: var– . The variable is initially used to provide a result before being decreased.

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

3. Assignment operators

To give a variable a value, assignment operators are employed. The following list of operators supported by the bc command:

val = value : Assign the value to the variable.

val += value : similar to val = val + value.

val -= value : similar to val = val – value.

val /= value : similar to val = val / value.

val ^= value : similar to val = val ^ value.

val %= value : similar to val = val % value.

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

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

4. Comparison or Relational Operators

To compare two numbers, relational operators logical are utilized. 1 is returned if the comparison is accurate. If false, it returns 0 else.

The following list of relational operators supported by the bc command, where p and q are variables :

p < q: Result is 1 if p is less than q.

p <= q: If p is smaller than or equal to q, the outcome will be 1.

p> q: If p is unambiguously greater than q, the result is 1.

p>= q: If p is bigger than or equal to q, the result is 1.

p== q: If p equals b, the outcome is 1.

p!= q: If p and q are not similar, the outcome will be 1.

$ echo "10>=5" | bc
1

$ echo "1!=2" | bc
1

5. Logical or Boolean operators

The BC command can also be used in conjunction with Bash’s logical operators, such as && and ||, which stand for logical addition and multiplication, respectively. Below are examples of boolean operations.

  • a && b: If both expressions are non-zero, the result will be 1.
  • a ||b: If each expression is non-zero, the result for a || b will be 1.
  • !a: If a is 0, the result will be 1.
$ echo "26 && 8" | bc
1

$ echo "0 || 0" | bc
0

$ echo "! 0" | bc
1

6. Math 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. The supported built-in math operations to operate the math functions are:

s (x): X’s sine, expressed in radians.

c (x): X’s cosine, expressed in radians.

l (x): Natural logarithm of x.

e(x): The exponential function that raises e to the value x.

J (n,x): The integer order n bessel function of x.

The following functions are also supported in addition to the math functions:

length(x) : Returns the total number of significant decimal digits of the expression.

read() : Reads the input value.

scale(expression) : The entire number of decimal digits after the decimal point is the value of scale.

sqrt(): This function is used to find the square root of the number.

ibase and obase: Specifies the basis for conversion of the input and output numbers. Base 10 is the default for both input and output.

last (an extension): A variable that contains the last displayed number’s value.

 Examples:

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

Here we set the shell variable pi’s value to “pi”. In this case, ‘a’ arctangent function which is included in the math library with the -l option is used.

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

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

$ echo "e(5)" | bc -l
148.41315910257660342111

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

$ echo "sqrt(4)" | bc
2

Some of the few examples to utilise ibase and obase are given below.

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

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

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

7. Conditional Statements

The use of a conditional if statement allows for the execution of assertions based on decisions that have been made.

Syntax:

if(condition) {statement} else {statement}

Example:

$ 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

8. Iterative Statements

The process of iteration involves repeating a series of instructions or statements for a certain number of times or up until a condition is satisfied.

Syntax:

for ( Assigning; condition; increment ){statement(s);}
while (condition){statements;}

Examples:

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

Below are some of the pseudo statement

break: This statement forces the most recent enclosing while or for statement to exit.

continue: The continue statement (an extension) instructs the most recent enclosing for statement to begin the next iteration.

return: It is used to return 0 from a function.

halt: When this statement is executed, it forces the bc processor to only exit.

limits: Print the regional restrictions that the local instance of bc imposes.

quit: The bc processor is stopped when the quit statement is read, regardless of where it is. For instance, bc ends when "if (0 == 1) quit".

warranty: Publish a notice of warranty.

Conclusion

In this tutorial, we have given various instances of utilizing the bc command in Linux. However, there is still more you can do with this potent command that you may discover on your own and use in your bash scripts to add more math and calculations.

Linux

Leave a Reply

Your email address will not be published. Required fields are marked *

Bash bc command in Linux – Usage + Examples

Have you wondered how to perform calculations in Linux and Unix systems? This mostly comes into use when you do programming.

In this tutorial, we learn about bc command in Linux with examples.

bash bc command

The bc command stands for the basic calculator. But also referenced as a bench calculator. It is used to perform basic mathematical calculations.

bc is commonly used in scripting and as well as in the interactive shell.

The most basic elements of bc are numbers. This command line calculator can handle the number of digits before the decimal and the number of digits after the decimal point. The second element is variables that can store numbers. That could be a simple variable or an array. bc also supports functions to perform standard mathematical operations.

Syntax

The basic syntax of bc command:

bc [ -hlwsqv ] [long-options] [ file ... ] 

Install bc in Linux

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

bc command Operations

bc command line calculator can perform arithmetic, Increment/decrement, assignment, logical or boolean, functions, statements, and store variables.

Let’s look into them with examples.

1. Arithmetic Operators

A mathematical function known as an arithmetic operator conducts a calculation on two operands. They are used in everyday math, and the majority of programming languages have a collection of them that may be utilized inside equations to carry out various kinds of sequential calculations.

Examples:

Addition

$ echo "10.5+5" | bc
5.5

We can use the following operators

(+) addition

(-) subtraction

(*) multiplication

(/) division

(%) Modulus

(^) exponent

A sample bash script

#! /bin/bash
echo "10+5" | bc
echo "scale=2;15.5/5" |bc

Where the scale function defines the number of decimal points you want.

2. Increment and decrement operators

Bash supports both the increment and decrement operators, just like other programming languages. By using the increment operator ++, a variable’s value is raised by one. Similarly, the decrement operator — reduces a variable’s value by one.

Pre-increment operator: ++var. Prior to using the variable’s outcome, the variable is first incremented.

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

Post increment operator: var++ . The variable is initially used to provide a result before being increased.

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

Pre-decrement operator: –var. Prior to using the variable’s outcome, the variable is first decreased.

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

Post-decrement operator: var– . The variable is initially used to provide a result before being decreased.

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

3. Assignment operators

To give a variable a value, assignment operators are employed. The following list of operators supported by the bc command:

val = value : Assign the value to the variable.

val += value : similar to val = val + value.

val -= value : similar to val = val – value.

val /= value : similar to val = val / value.

val ^= value : similar to val = val ^ value.

val %= value : similar to val = val % value.

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

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

4. Comparison or Relational Operators

To compare two numbers, relational operators logical are utilized. 1 is returned if the comparison is accurate. If false, it returns 0 else.

The following list of relational operators supported by the bc command, where p and q are variables :

p < q: Result is 1 if p is less than q.

p <= q: If p is smaller than or equal to q, the outcome will be 1.

p> q: If p is unambiguously greater than q, the result is 1.

p>= q: If p is bigger than or equal to q, the result is 1.

p== q: If p equals b, the outcome is 1.

p!= q: If p and q are not similar, the outcome will be 1.

$ echo "10>=5" | bc
1

$ echo "1!=2" | bc
1

5. Logical or Boolean operators

The BC command can also be used in conjunction with Bash’s logical operators, such as && and ||, which stand for logical addition and multiplication, respectively. Below are examples of boolean operations.

  • a && b: If both expressions are non-zero, the result will be 1.
  • a ||b: If each expression is non-zero, the result for a || b will be 1.
  • !a: If a is 0, the result will be 1.
$ echo "26 && 8" | bc
1

$ echo "0 || 0" | bc
0

$ echo "! 0" | bc
1

6. Math 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. The supported built-in math operations to operate the math functions are:

s (x): X’s sine, expressed in radians.

c (x): X’s cosine, expressed in radians.

l (x): Natural logarithm of x.

e(x): The exponential function that raises e to the value x.

J (n,x): The integer order n bessel function of x.

The following functions are also supported in addition to the math functions:

length(x) : Returns the total number of significant decimal digits of the expression.

read() : Reads the input value.

scale(expression) : The entire number of decimal digits after the decimal point is the value of scale.

sqrt(): This function is used to find the square root of the number.

ibase and obase: Specifies the basis for conversion of the input and output numbers. Base 10 is the default for both input and output.

last (an extension): A variable that contains the last displayed number’s value.

 Examples:

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

Here we set the shell variable pi’s value to “pi”. In this case, ‘a’ arctangent function which is included in the math library with the -l option is used.

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

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

$ echo "e(5)" | bc -l
148.41315910257660342111

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

$ echo "sqrt(4)" | bc
2

Some of the few examples to utilise ibase and obase are given below.

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

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

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

7. Conditional Statements

The use of a conditional if statement allows for the execution of assertions based on decisions that have been made.

Syntax:

if(condition) {statement} else {statement}

Example:

$ 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

8. Iterative Statements

The process of iteration involves repeating a series of instructions or statements for a certain number of times or up until a condition is satisfied.

Syntax:

for ( Assigning; condition; increment ){statement(s);}
while (condition){statements;}

Examples:

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

Below are some of the pseudo statement

break: This statement forces the most recent enclosing while or for statement to exit.

continue: The continue statement (an extension) instructs the most recent enclosing for statement to begin the next iteration.

return: It is used to return 0 from a function.

halt: When this statement is executed, it forces the bc processor to only exit.

limits: Print the regional restrictions that the local instance of bc imposes.

quit: The bc processor is stopped when the quit statement is read, regardless of where it is. For instance, bc ends when "if (0 == 1) quit".

warranty: Publish a notice of warranty.

Conclusion

In this tutorial, we have given various instances of utilizing the bc command in Linux. However, there is still more you can do with this potent command that you may discover on your own and use in your bash scripts to add more math and calculations.

Linux

Leave a Reply

Your email address will not be published. Required fields are marked *

Bash bc command in Linux – Usage + Examples

Have you wondered how to perform calculations in Linux and Unix systems? This mostly comes into use when you do programming.

In this tutorial, we learn about bc command in Linux with examples.

bash bc command

The bc command stands for the basic calculator. But also referenced as a bench calculator. It is used to perform basic mathematical calculations.

bc is commonly used in scripting and as well as in the interactive shell.

The most basic elements of bc are numbers. This command line calculator can handle the number of digits before the decimal and the number of digits after the decimal point. The second element is variables that can store numbers. That could be a simple variable or an array. bc also supports functions to perform standard mathematical operations.

Syntax

The basic syntax of bc command:

bc [ -hlwsqv ] [long-options] [ file ... ] 

Install bc in Linux

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

bc command Operations

bc command line calculator can perform arithmetic, Increment/decrement, assignment, logical or boolean, functions, statements, and store variables.

Let’s look into them with examples.

1. Arithmetic Operators

A mathematical function known as an arithmetic operator conducts a calculation on two operands. They are used in everyday math, and the majority of programming languages have a collection of them that may be utilized inside equations to carry out various kinds of sequential calculations.

Examples:

Addition

$ echo "10.5+5" | bc
5.5

We can use the following operators

(+) addition

(-) subtraction

(*) multiplication

(/) division

(%) Modulus

(^) exponent

A sample bash script

#! /bin/bash
echo "10+5" | bc
echo "scale=2;15.5/5" |bc

Where the scale function defines the number of decimal points you want.

2. Increment and decrement operators

Bash supports both the increment and decrement operators, just like other programming languages. By using the increment operator ++, a variable’s value is raised by one. Similarly, the decrement operator — reduces a variable’s value by one.

Pre-increment operator: ++var. Prior to using the variable’s outcome, the variable is first incremented.

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

Post increment operator: var++ . The variable is initially used to provide a result before being increased.

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

Pre-decrement operator: –var. Prior to using the variable’s outcome, the variable is first decreased.

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

Post-decrement operator: var– . The variable is initially used to provide a result before being decreased.

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

3. Assignment operators

To give a variable a value, assignment operators are employed. The following list of operators supported by the bc command:

val = value : Assign the value to the variable.

val += value : similar to val = val + value.

val -= value : similar to val = val – value.

val /= value : similar to val = val / value.

val ^= value : similar to val = val ^ value.

val %= value : similar to val = val % value.

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

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

4. Comparison or Relational Operators

To compare two numbers, relational operators logical are utilized. 1 is returned if the comparison is accurate. If false, it returns 0 else.

The following list of relational operators supported by the bc command, where p and q are variables :

p < q: Result is 1 if p is less than q.

p <= q: If p is smaller than or equal to q, the outcome will be 1.

p> q: If p is unambiguously greater than q, the result is 1.

p>= q: If p is bigger than or equal to q, the result is 1.

p== q: If p equals b, the outcome is 1.

p!= q: If p and q are not similar, the outcome will be 1.

$ echo "10>=5" | bc
1

$ echo "1!=2" | bc
1

5. Logical or Boolean operators

The BC command can also be used in conjunction with Bash’s logical operators, such as && and ||, which stand for logical addition and multiplication, respectively. Below are examples of boolean operations.

  • a && b: If both expressions are non-zero, the result will be 1.
  • a ||b: If each expression is non-zero, the result for a || b will be 1.
  • !a: If a is 0, the result will be 1.
$ echo "26 && 8" | bc
1

$ echo "0 || 0" | bc
0

$ echo "! 0" | bc
1

6. Math 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. The supported built-in math operations to operate the math functions are:

s (x): X’s sine, expressed in radians.

c (x): X’s cosine, expressed in radians.

l (x): Natural logarithm of x.

e(x): The exponential function that raises e to the value x.

J (n,x): The integer order n bessel function of x.

The following functions are also supported in addition to the math functions:

length(x) : Returns the total number of significant decimal digits of the expression.

read() : Reads the input value.

scale(expression) : The entire number of decimal digits after the decimal point is the value of scale.

sqrt(): This function is used to find the square root of the number.

ibase and obase: Specifies the basis for conversion of the input and output numbers. Base 10 is the default for both input and output.

last (an extension): A variable that contains the last displayed number’s value.

 Examples:

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

Here we set the shell variable pi’s value to “pi”. In this case, ‘a’ arctangent function which is included in the math library with the -l option is used.

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

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

$ echo "e(5)" | bc -l
148.41315910257660342111

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

$ echo "sqrt(4)" | bc
2

Some of the few examples to utilise ibase and obase are given below.

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

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

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

7. Conditional Statements

The use of a conditional if statement allows for the execution of assertions based on decisions that have been made.

Syntax:

if(condition) {statement} else {statement}

Example:

$ 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

8. Iterative Statements

The process of iteration involves repeating a series of instructions or statements for a certain number of times or up until a condition is satisfied.

Syntax:

for ( Assigning; condition; increment ){statement(s);}
while (condition){statements;}

Examples:

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

Below are some of the pseudo statement

break: This statement forces the most recent enclosing while or for statement to exit.

continue: The continue statement (an extension) instructs the most recent enclosing for statement to begin the next iteration.

return: It is used to return 0 from a function.

halt: When this statement is executed, it forces the bc processor to only exit.

limits: Print the regional restrictions that the local instance of bc imposes.

quit: The bc processor is stopped when the quit statement is read, regardless of where it is. For instance, bc ends when "if (0 == 1) quit".

warranty: Publish a notice of warranty.

Conclusion

In this tutorial, we have given various instances of utilizing the bc command in Linux. However, there is still more you can do with this potent command that you may discover on your own and use in your bash scripts to add more math and calculations.

Linux

Leave a Reply

Your email address will not be published. Required fields are marked *