Linux bc command

The bc command in Linux is a calculator that provides arithmetic and mathematical operations within the command line interface. It supports basic arithmetic, advanced mathematical functions, and even allows the use of variables and control structures.

Here’s an overview of how to use the bc command:

  1. Basic Arithmetic:
    The bc command can be used for basic arithmetic calculations. You can simply type the mathematical expression directly into the bc prompt. For example:
   2 + 2
  1. Mathematical Functions:
    bc supports a wide range of mathematical functions such as sine, cosine, logarithm, exponentiation, and more. These functions are accessed by using the bc command in combination with the scale variable. The scale variable specifies the number of decimal places to display in the result. For example:
   echo "scale=2; sqrt(9)" | bc -l
  1. Using Variables:
    bc allows you to define and use variables within your calculations. To define a variable, use the = symbol. For example:
   echo "var = 5; var * 2" | bc
  1. Control Structures:
    bc also supports control structures like loops and conditionals. You can use the for, while, and if statements within bc to perform iterative calculations or condition-based operations. Here’s an example of using a loop in bc:
   echo "for (i = 1; i <= 5; i++) i" | bc
  1. Reading from Files:
    Instead of typing the calculations directly into the bc prompt, you can also provide input from a file. For example, if you have a file called input.txt containing the mathematical expression, you can use the following command:
   bc < input.txt
  1. Examples:
  • Perform a basic arithmetic calculation: echo "2 + 2" | bc
  • Calculate the square root of a number with a specific decimal precision: echo "scale=3; sqrt(16)" | bc -l
  • Use variables in calculations: echo "var = 5; var * 2" | bc
  • Perform iterative calculations using a loop: echo "for (i = 1; i <= 10; i++) i" | bc
  • Read input from a file:
    bc < input.txt

The bc command provides a powerful calculator functionality within the command line interface. It can handle basic arithmetic, advanced mathematical functions, variables, and control structures, making it a versatile tool for mathematical calculations and scripting.

For more information about the bc command and its options, you can refer to the manual page by typing man bc in your terminal.