bc Command in Linux | Explained

The “bc” command in Linux is the abbreviation for the “Basic Calculator”. It is a pre-installed command-line utility for Linux. Using the “bc” command, users can perform basic mathematical operations right from the terminal. The operations include Addition, Subtraction, Multiplication, Division, and several built-in math functions. The “bc” command’s syntax matches with that of the C language. 

The “bc” utility can also operate using the variables, handle the algebra, and convert the numbers from one system to another. It can work with integer and floating-point numbers with high accuracy & precision.

A detailed explanation of the “bc command is demonstrated in this post.

Content Covered

How Does the bc Command Work in Linux?

The “bc” command processes the code from the provided files and reads the standard input. It can also be invoked directly from the terminal and users can perform the mathematical operations without using the files or scripts. The bc command is stored in the “/usr/bin/bc” file. 

Syntax

The syntax of the “bc” command is as follows:

bc [options] [file ...]

Here, 

  • bc: It invokes the bc (basic calculator) command-line utility.
  • options: A list of options for your requirements is provided below.
  • file: It is the file name on which you want to use the bc command.

Let us understand the options or flags of the bc command.

bc Command Options

The bc command currently supports the following options:

-h or –helpDisplays the help page that shows the supported options.
-i or –interactive Forces the interactive mode that allows users to perform calculations from the terminal.
-l or –mathlibAllows predefined math functions with advanced capabilities. It lets you use sine, cosine, tangent, and mathematical functions. It also sets the scale variable to 20, whose default value is “0”.
-q or –quietPrevents the version and the copyright information from appearing after entering the interactive mode.
-s or –standardMakes the bc command ignore all extensions and process as the standard POSIX.
-w or –warnWarns the users about the use of POSIX bc extensions.
-v or –versionDisplays the current version of the bc utility.

Things to Learn Before Using the bc Command

A few essential notes must be understood before using the bc command in Linux:

  1. The semicolon ; tells the “bc” command that it is the end of the line.
  2. Users must define the function before calling it.
  3. If no file is specified, the bc command will run from the terminal and you can use it as the scientific calculator.

How to Install the bc Command in Linux?

Although the bc command-line utility is already installed on Linux, some users reported getting the error “bc command not found”. It is because your system does not have the bc command installed in it. To install the bc command, run the following commands based on your distro:

sudo apt install bc #For Debian/Ubuntu
sudo dnf install bc #For Fedora 22+sudo yum install bc #For RHEL/CentOS

How to Use the bc Command in Linux?

To use the bc command in Linux, enter bc in your system’s terminal, which will start interactively. You can now use your terminal as the calculator, as illustrated in the examples below:

Example 1: Performing Arithmetic Calculations 

Here, we will perform simple arithmetic calculations using the bc command. To do that, invoke the bc command interactive mode using the “bc” or “bc -i” command (both are the same commands) and then perform the operations:

After invoking the bc command, we performed simple arithmetic operations from the terminal screen.

Example 2: Performing Arithmetic Calculations Using an Input File

The bc command accepts the input file and displays the output on the terminal screen. To open and view the output of the calculations in the file, provide the file name or path as follows:

cat Calculation.txt
bc -l Calculation.txt

The above scenario is explained as follows:

  • After creating the file, we used the cat Command to view its contents.
  • Using the “bc -l” command, we invoked the bc command. The “-l” flag changes the scale’s (decimal places) to 20.
  • The “Calculation.txt” is the file name on which the bc command will work.

Once the bc command has read the file, you will see the output of the calculations.

Note: If there is a syntax or any other error in the file, it will still go through the whole file, print the output, and display the error on the specific line.

Example 3: Finding the Square Root

Since the bc command supports the predefined Math functions with advanced capabilities such as finding the square root. To find the square root, we will use the “sqrt” function of Math after using the bc command:

bc
sqrt (100)
sqrt (100) + sqrt (25)

The above scenario is explained as follows:

  • The “bc” invokes the command.
  • The “sqrt (100)” calculates and displays the square root of 100.
  • The “sqrt (100)” and “sqrt (25)” calculate, add, and display the sum of the square root of 100 and 25 which is 15. 

Additional mathematical functions supported by the bc command include the following:

  1. s (value): Use this to find the sin of the specified “value”. The input value is always in radians.
  2. c (value): Use this to find the cos of the specified “value”. The input value is taken in as the radians.
  3. a (value): Use this option to find the arc tangent of the specified “value”, it returns the output in radians.
  4. l (value): Use this to find the natural logarithm of the specified value.
  5. e (value): The exponential function is utilized to raise e to the specified value.
  6. sqrt(value): Use this to calculate the square root of the specified value. An error will arise if the input value is negative.

Example 4: Using the Scale Variable to Specify the Decimal Places

Using the scale variable in the bc command, users can specify the number of digits after the decimal places. It allows the users to view the output of their code with more clarity and the output is more precise. The scale variable is used in the following way:

bc -q
scale = 3

The above scenario is explained as follows:

  • The “bc -q” invokes the bc command without displaying the version and copyright information.
  • The “scale =3” sets the scale variable to 3 and it will make the echo command display only 3 digits after the decimal point.

Note: To change the value of the scale variable, use the “scale = value” format.

Example 5: Using the bc Command With the echo Command

The bc command can be used without invoking it in the terminal. It requires the echo command, as seen below:

echo "1000 + 1000" | bc

The above scenario is explained as follows:

  • 1000 + 1000” is the equation.
  • The “| bc” pipelines the echo command with the bc command. It displays the output (2000) of the equation which is processed by the “bc command”.

Example 6: Using the bc Command to Convert Number Systems

The number systems are required to characterize the numbers in a structured symbol set. These numbers of systems can be converted from one to another using the bc command in Linux.

Note: The default number system used by the bc command is the Decimal Number System.

Converting the Decimal to the Hexadecimal

Use the bc command as in the following format for converting from Decimal to Hexadecimal and change the number according to your requirements:

echo 'obase=16; 230' | bc

The above scenario is explained as follows:

  • The “echo” command displays the output.
  • The “‘obase=16; 230’” converts the number (230) from the decimal (default) to the hexadecimal or base 16. The “obase” stands for the output base.

Converting the Decimal to the Binary

The default number system used by the bc command is the decimal. Let’s suppose convert 230 from the Decimal number system to the Binary number system using the bc command:

echo 'obase=2; 230' | bc

The above scenario is explained as follows:

  • The “‘obase=2; 230’ | bc” converts the number (230) from the decimal (default) to the binary or base 2.
  • The output (11100110) is then displayed via the “echo” command.

Convert from Binary to Decimal

To convert a number from the binary number system to the decimal number system, provide the “ibase” or “input base” as seen below:

echo 'obase=10; ibase=2; 11100110' | bc

The above scenario is explained as follows:

  • The “‘obase=10; ibase=2; 11100110’ | bc” converts the binary number (11100110) from the binary number system to the decimal number system that outputs 230.

Convert from Hexadecimal to Decimal

To convert a number from the binary number system to the decimal number system, the “ibase” or “input base” is required. The conversions allow enhanced human readability. Let’s convert from FF (from hexadecimal) to the decimal number system:

echo 'obase=10; ibase=16; FF' | bc

The above scenario is explained as follows:

  • The “obase=10” is the output number system.
  • The “ibase=16” is the input number system.
  • The “FF” is the number in the hexadecimal or base 16 number system. It outputs 255 after conversion.

Example 7: Using the bc Command to Convert the Temperature From Celsius to Fahrenheit 

Below is an example of converting the temperature from Celsius to Fahrenheit. It is often considered to make the temperature more readable per your geographic location. It is done using a text file: 

scale=3
print "\n This program converts the temperature from Celsius to Fahrenheit \n\n\n"
print "Please enter the temperature in Celsius"; cel = read()
print "\n\n"
print "The temperature after conversion is :"
(cel * 9/5 + 32)
quit

The file is named script.txt and you can view its content using the cat command and edit it using the nano editor (highly recommended). To execute the code in the file, run the bc command, enter the desired option (-q to suppress the version and copyright information), and then enter the file name/path:

cat script.txt
bc -q script.txt

The above scenario is explained as follows:

  • The “cat script.txt” command opens the script.txt file in the terminal. It is read-only.
  • In the “script.txt” file, we have set the “scale” variable to 3. Following that, some text is printed using the echo command. After the user enters a number that will be converted to Fahrenheit, it will be stored in the “cel” variable using the “read()” function (built-in).
  • Next, the conversion formula is used and the output is displayed.
  • The “quit” closes the file after the code execution is complete.

Example 8: Using the bc Command to Calculate the Natural Logarithm 

The bc command of Linux supports the logarithmic functions that can be used when the “-l” option is used, as seen below:

echo 'l(20)' | bc -l

The above scenario shows that:

  • The ‘l(20)’ is used to calculate the natural log of 20. 
  • The “bc -l” is needed to use the math functions.

Example 9: Using the Loops in the bc Command 

The bc command of Linux supports loops that can allow the users to do repetitive tasks with ease. The use of loops in the Linux bc command is explained as follows:

Using the for Loop With the bc Command

The use of the for loop in the bc command is straightforward and is used as seen below:

echo "for (k=1;k<=7;k++) { print k}" |bc

In the above scenario, the loop runs 7 times and prints the numbers from 1 to 7 and the output is piped to the bc command.

Using the while Loop With the bc Command

The while loop executes a block of code until a certain condition is met. The bc command supports the while loop and its use is illustrated below:

echo "k=1;while (k<=20) {k; k+=2}” |bc

The while loop will continue to run until the value of k is less than or equal to 20. It works by incrementing the value of k by 2 and displaying it. 

Example 10: Using the Increment Operators in the bc Command 

The bc command can be used with the increment operators, which is illustrated below:

Using the Pre-Increment Operator in the bc Command

The pre-increment operator is used to increment a value which is then stored in a variable. For a better understanding, look at the below command:

echo "val=15; ++val" |bc

The command shows that the pre-increment operator stores the value (15) to the variable (val) and then applies the increment and then displays the output (16).

Using the Post-Increment Operator in the bc Command

The post-increment operator is used to increment a value after it is stored in a variable. Let’s understand it using the below example:

echo "val=15; val++" |bc

The command shows that the post-increment operator first stores the value (15) to the variable (val) and then applies the increment so the output (15) remains the same.

Example 11: Using the if Condition With the bc Command 

The bc command supports the use of “if” or conditional statements. The use of the “if” statement with the bc command is illustrated below:

echo 'a=20;b=30; if(a>b) print "\n a is greater \n" else print "\n b is greater \n" ' | bc -l

In this example:

  • The “a” is assigned 20 and “b” is assigned 30.
  • After assigning, the “if” block starts in which “a” and “b” are compared (a>b).
  • Based on the output of the conditions, the text is displayed on the terminal screen. It will output that the “b is greater” as the value of the b variable is more.
  • The bc command is used with the “-l” flag that allows the use of the predefined math operations.

Example 12: Using the Logical or Boolean Operators With the bc Command 

The logical or Boolean operators are often utilized in conditional statements. The output of these operators is “1” or “TRUE” and “0” or “FALSE”. Here are the results you will get when using the logical or Boolean operators with the bc command:

  1. Value1 && Value2: This results in “1” when both the values are non-zero.
  2. Value1 || Value2: This results in “1” when either one of the values is non-zero.
  3. ! Value: This results in “1” if the value is zero.

Here is the visual representation of the above statements:

echo "1 && 2" | bc
echo "1 || 2" | bc
echo "! 0" | bc

In the above example:

  • The first command checks if the values (1 and 2) are non-zero and displays “1”, which stands for true.
  • The second command checks if either of the values is non-zero and displays “1”, which stands for true.
  • The third command checks if the value is zero and displays “1”, which stands for true.

That’s about it for today’s post.

Final Words

The “bc” or “Basic Calculator” command-line utility in Linux performs several mathematical operations from the terminal. It comes with several built-in math functions such as square root, logarithm, which can be used via the “-l” option or flag. The bc command also supports loops, conditional statements, and logical or Boolean operators as explained in this guide.