Linux bc Command

Linux 命令大全Linux Command Reference

The bc command is an arbitrary precision calculator language, usually used as a calculator under Linux.

It is similar to a basic calculator, and you can use this calculator to perform basic mathematical operations.

Common operations:

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • ^ Exponentiation
  • % Remainder

Syntax

bc(选项)(参数)

Options

  • -i: Force entering interactive mode;
  • -l: Define the standard math library to use;
  • -w: Give warning messages for extensions to POSIX bc;
  • -q: Do not print the normal GNU bc environment information;
  • -v: Display instruction version information;
  • -h: Display instruction help information.

Parameters

File: Specify the file containing the calculation tasks.

Examples

$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2+3
5
5-2
3
2+3*1
5

Type quit to exit.

Via pipe symbol

$ echo "15+5" | bc
20

scale=2 sets the decimal places; 2 means keep two decimal places:

$ echo 'scale=2; (2.777 - 1.4744)/1' | bc
1.30

In addition to using scale to set decimal places, bc also has ibase and obase for operations in other bases:

$ echo "ibase=2;111" |bc
7

Base conversion

#!/bin/bash

abc=192 
echo "obase=2;$abc" | bc

The result is: 11000000. This uses bc to convert decimal to binary.

#!/bin/bash 

abc=11000000 
echo "obase=10;ibase=2;$abc" | bc

The result is: 192. This uses bc to convert binary to decimal.

Calculate square and square root:

$ echo "10^10" | bc 
10000000000
$ echo "sqrt(100)" | bc
10

Linux 命令大全Linux Command Reference

Other Extensions