bc Command in Linux

FREE Online Courses: Dive into Knowledge for Free. Learn More!

In this article, we will learn everything about the bc command in Linux. We will look at what the bc command is, its purpose, the syntax of the bc command, the options used along with the command, and the operators supported by the bc command. We will also look at a practical example in the terminal of Ubuntu 20.04 for each type of operator to understand their functioning.

What is Linux bc command?

Bc is a command-line-based utility in Linux and Unix-based operating systems used as a calculator. Calling the bc command a “calculator” somewhat makes it look naive and basic, but the bc command is capable of complex numerical, which consist of various numbers and operators. It can even handle interactive statements like for loop.

When we say calculator, we think of the calculator on the GUI of your computer, but the calculator in the terminal is far superior. Apart from solving your day-to-day arithmetic tasks, the bc command can also do things like algebra, handling variables, converting numbers to hexadecimal, iterative statements, conditional statements, math functions, and more.

In a nutshell, the bc command is a command-line advanced scientific calculator. We generally use the bc command by piping it with the echo command, as the output will be passed in as the input for the bc command.

Syntax of bc command in Linux

The syntax of the bc command is extremely easy. See for yourself:

bc <options> <filename>

Options used along with the bc command

Unlike most of the commands in Linux, the bc command has only a few options associated with it. Let us take a brief look at each one of them:

1. -h

This option prints the help menu of the bc command, as shown below:

help

2. -i

This option forces the bc command to interactive mode. You can also write this option as “–interactive.”

3. -l

This option defined the standard math library. You can also write this option as “–mathlib.”

4. -w

This option gives warnings for extensions to POSIX bc. You can also write this option as “–warn.”

5. -s

This option processes the POSIX bc language. You can also write this option as “–standard.”

6. -q

This option does not print the normal GNU bc welcome. You can also write this option as “–quiet.”

7. -v

This option prints the information about the version of the bc command:

version

Features of bc command in Linux

Remember that we touch on some of the many great and superior features of the bc command, well here is the complete list of the features the bc command supports:

1. Arithmetic operators
2. Increment or Decrement operators
3. Assignment operators
4. Relational operators
5. Logical or Boolean operators
6. Math functions
7. Conditional statements
8. Iterative statements

Let us look at each of the features in slightly more detail, along with some examples, to understand them better.

1. Linux Arithmetic operators

Arithmetic operators consist of basic daily math problems involving addition, subtraction, division, multiplication, exponents, and modulus division. To perform such operations, all you have to do is to pipe the bc command with an echo command which contains the problem. Use the syntax shown below:

echo “<num1> <operator> <num2>” | bc

arithmetic

Storing a value in a variable

Remember that I told you that the bc command could handle variables? Well, it can, but how do we store a value in a variable? We simply put the variables in front of the echo command, and when we want to print the answer, we call the variable using the echo command by preceding it with a dollar sign. Use the syntax shown below:

<variable>=`echo “<num1> <operator> <num2>” | bc`
echo $<variable>

storing value

2. Assignment operators in Linux

Assignment operators are more like a shortcut for writing long arithmetic numerals. Let us look at them to get a better idea of how they work:

1. variable = value: assigning a value to a variable
2. variable += value : same as (variable = variable + value)
3. variable -= value :same as (variable = variable – value)
4. variable *= value : same as (variable = variable * value)
5. variable /= value : same as (variable = variable / value)
6. variable ^= value : same as (variable = variable ^ value)
7. variable %= value : same as (variable = variable % value)

Note: we can combine multiple echo statements by simply separating them by a semicolon (;)

Let us look at an example for each of the seven assignment variables to understand their working better.

assignment

3. Linux Increment and decrement operators

Increment operators are also another way of writing arithmetic numerical in short notation. Let us look at them to get a better idea of how they work:

a. variable++

The increment operator is the same as (variable=variable+1) or (variable+=1). This operator is called the post-increment operator, as the variable result is used first, and then the variable is incremented.

b. ++variable

The increment operator is the same as (variable=variable+1) or (variable+=1). You must be wondering, as this is similar to the “variable++” operator. Well, there is one key difference – this operator is called the pre-increment operator, as the variable is increased first, and then the variable result is stored.

c. variable–

The increment operator is the same as (variable=variable-1) or (variable-=1). This operator is called the post-decrement operator, as the variable result is used first, and then the variable is decreased.

d. –variable

The increment operator is the same as (variable=variable-1) or (variable-=1). Therefore, you might think this is similar to the “variable–” operator. However, there is one key difference – This operator is called the pre-decrement operator, as the variable is decreased first, and then the variable result is stored.

Let us look at an example for each of the four assignment variables to understand their working better.

increment decrement

4. Linux Relational operators

Relational operators are used for comparing two numbers. If it is true, the result is 1. Otherwise (if the comparison is true), the result is 0. Let us look at them to get a better idea of how they work:

1. expr1<expr2 : Outputs 1 if expr1 is less than expr2.
2. expr1<=expr2 : Outputs 1 if expr1 is less than or equal to expr2.
3. expr1>expr2 : Outputs 1 if expr1 is greater than expr2.
4. expr1>=expr2 : Outputs 1 if expr1 is greater than or equal to expr2.
5. expr1==expr2 : Outputs 1 if expr1 is equal to expr2.
6. expr1!=expr2 : Outputs 1 if expr1 is not equal to expr2.

Let us look at an example for each of the six assignment variables to understand their working better.

relational

5. Linux Logical operators

Logical operators are slightly more intimidating. Thankfully there are only a few of them. We will be mainly focusing on: “Logical and”, “Logical or”, and “Logical negation (!)”. These are used to club two or more relational statements to narrow down the condition even more. Let us look at how these work before we see an example.

a. Logical and operator (&&) 

The “logical and operator” will be true if the conditions are true. If not, it will be false, meaning it will be false if any one or both of the conditions are true. It is denoted by two ampersand symbols (&&). To understand this operator better, let us look at the truth table enclosed with different scenarios:

NOCONDITION  1CONDITION 2CONDITION  1 && CONDITION  2
1TRUE (1)TRUE (1)TRUE (1)
2TRUE (1)FALSE (0)FALSE (0)
3FALSE (0)TRUE (1)FALSE (0)
4FALSE (0)FALSE (0)FALSE (0)

Let us now look at the above table in form of an example to understand this operator fully:

logical

b. Logical or operator (||) 

The “logical or operator” will be true if any one of the conditions is true, and it will be false if both the conditions are false. It is denoted by two pipe symbols (||). To understand this operator better, let us look at the truth table enclosed with different scenarios:

NOCONDITION  1CONDITION 2CONDITION  1 || CONDITION  2
1TRUE (1)TRUE (1)TRUE (1)
2TRUE (1)FALSE (0)TRUE (1)
3FALSE (0)TRUE (1)TRUE (1)
4FALSE (0)FALSE (0)FALSE (0)

Let us now look at the above table as an example to understand this operator fully!

c. Logical negation (!) 

This operator is pretty simple. It simply inverts the truth value, and if it is true, it will become false, and vice versa:

NOCONDITION  ! CONDITION 
1TRUEFALSE
1FALSETRUE

Let us now look at the above table in form of an example to understand this operator fully:

logical negation

6. Linux Mathematical functions

The bc command also has many in-built maths functions. Let us look at what they are and their uses.

1. s (x): The sine of x, the value of x is in radians.
2. c (x): The cosine of x, the value of x is in radians.
3. a (x): The arctangent of x, arctangent returns radians.
4. l (x): The natural logarithm of x.
5. e (x): The exponential function of raising e to the value x.
6. j (n,x) : The Bessel function of integer order n of x.
7. sqrt(x) : Square root of the number x.
8. length(x) : Returns the number of digits in x.
9. read(): Reads the number from the standard input.
10. scale(expression): The value of the scale function is the number of digits after the decimal point in the expression.
11. ibase and obase: Used to convert decimal to binary and vice versa
12. last (an extension): is a variable with the value of the last printed number.

Let us look at some examples of these math functions in action to understand better how they work.

mathematical

7. Linux Conditional statements

Conditional statements are nothing but if-else statements. They are used to make decisions and execute statements based on these decisions. It means that if the conditions are true, it will execute a specific set of statements, and if the conditions are false, it will execute another set of statements. The syntax of the if statement is:

if(condition) {statements} else {statements}

if(condition) {statements} else {statements}

conditional

8. Linux Iterative statements

Loops or iterative statements repeat a set of statements until the conditions specified are false. The bc command supports the for loop and while loop. The for loop syntax is: for(assignment; condition; update) {statments}

The while loop syntax is:

while(condition){statments}

Here is an example of printing numbers 1 to 10 using both for loop and while loop:

iterative

while

While using conditional statements and iterative statements, we sometimes use a few pseudo statements when a certain condition is met. Let us look at the pseudo statements supported by the bc command.

a. Break

This statement causes a forced exit of the most recent enclosing while statement or for statement.

b. Continue

This statement causes the most recent enclosing statement to start the next iteration.

c. halt

This statement is an executed statement that causes the bc processor to quit only when it is executed.

d. return

Return the value 0 from a function. (See the section on functions).

e. return(expression)

This statement returns the value of the expression from a function.

f. limits

This statement prints the local limits enforced by the local version of bc.

g. quit

This statement terminates the bc processor.

h. warranty

This statement prints a warranty notice.

Functions in Linux

The bc command also supports functions. Functions are one of the most powerful tools for any programming language, as you can choose what happens in your custom-made function. Once you have built your function, you can call it where you want it with the appropriate input and get the desired output. The syntax for writing a function is shown below:

define <function name>(parameters) 
{
        statements...
        .....................
        return statement
}

Using Linux bc command with a file

In the syntax of the bc command, we have a field called <filename>. What exactly is this for? We can write our arithmetic operations in a file and then use the bc command followed by the filename to execute our text file.

We first use the cat command along with a redirection operator to write our problems and then use the bc command followed by the filename. Here is an example illustrating the same:

example

We have gotten our desired output, but there is one tiny problem – the bc command prints unnecessary messages. To avoid printing this, pair the bc command with the option “-q,” as shown below:

bc -q <filename>

pair

Summary

As you have seen, the bc command is far more than a calculator. It is simple yet advanced for it to be compared to the awk command – a one-line scripting command. You have now understood what the bc command is, its purpose, the syntax of the command, the options used, and the various features supported by the bc command. We have explored each operator and feature with the help of at least one example to provide us with a better picture of its working.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

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