Linux bc Command
The bc command is an arbitrary-precision calculator language, usually used as a calculator under Linux.
It is similar to a basic calculator; you can use it to perform basic mathematical operations.
Common operations:
-
- Addition
-
- Subtraction
-
- Multiplication
- / Division
- ^ Exponentiation
- % Remainder
Syntax
bc(选项)(参数)
Option values
- -i: Force interactive mode;
- -l: Define the standard math library to use
- ; -w: Give warnings about extensions to POSIX bc;
- -q: Do not print the normal GNU bc environment information;
- -v: Display the command version information;
- -h: Display the command help information.
Parameters
file: Specify the file containing the calculation tasks.
Example
$ 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.
Through the pipe
$ echo "15+5" | bc
20
scale=2 sets the number of decimal places; 2 means keep two digits:
$ echo 'scale=2; (2.777 - 1.4744)/1' | bc
1.30
In addition to scale for setting decimal places, bc also has ibase and obase for operations in other number bases:
$ echo "ibase=2;111" |bc
7
Number base conversion
#!/bin/bash
abc=192
echo "obase=2;$abc" | bc
The result is: 11000000, which converts decimal to binary using bc.
#!/bin/bash
abc=11000000
echo "obase=10;ibase=2;$abc" | bc
The result is: 192, which converts binary to decimal using bc.
Calculate the square and square root:
$ echo "10^10" | bc
10000000000
$ echo "sqrt(100)" | bc
10
Linux Command Reference