bc : 一个命令行计算器
bc 命令 计算器
![](/data/attachment/album/201608/06/182300kcj29vz3qmpjs9xm.jpg)


假如你在一个图形桌面环境中需要一个计算器时，你可能只需要一路进行点击便可以找到一个计算器。例如，Fedora 工作站中就已经包含了一个名为 `Calculator` 的工具。它有着几种不同的操作模式，例如，你可以进行复杂的数学运算或者金融运算。但是，你知道吗，命令行也提供了一个与之相似的名为 `bc` 的工具？


`bc` 工具可以为你提供的功能可以满足你对科学计算器、金融计算器或者是简单计算器的期望。另外，假如需要的话，它还可以从命令行中被脚本化。这使得当你需要做复杂的数学运算时，你可以在 shell 脚本中使用它。


因为 bc 也被用于其他的系统软件，例如 CUPS 打印服务，所以它可能已经在你的 Fedora 系统中被安装了。你可以使用下面这个命令来进行检查：



```
dnf list installed bc

```

假如因为某些原因你没有在上面命令的输出中看到它，你可以使用下面的这个命令来安装它：



```
sudo dnf install bc

```

### 用 bc 做一些简单的数学运算


使用 bc 的一种方式是进入它自己的 shell。在那里你可以按行进行许多次计算。当你键入 bc 后，首先出现的是有关这个程序的警告：



```
$ 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'.

```

现在你可以按照每行一个输入运算式或者命令了：



```
1+1

```

bc 会回答上面计算式的答案是：



```
2

```

在这里你还可以执行其他的命令。你可以使用 加（+）、减（-）、乘（\*）、除（/）、圆括号、指数符号（^） 等等。请注意 bc 同样也遵循所有约定俗成的运算规则，例如运算的先后顺序。你可以试试下面的例子：



```
(4+7)*2
4+7*2

```

若要退出 bc 可以通过按键组合 `Ctrl+D` 来发送 “输入结束”信号给 bc 。


使用 bc 的另一种方式是使用 `echo` 命令来传递运算式或命令。下面这个示例就是计算器中的 “Hello, world” 例子，使用 shell 的管道函数（|） 来将 `echo` 的输出传入 `bc` 中：



```
echo '1+1' | bc

```

使用 shell 的管道，你可以发送不止一个运算操作，你需要使用分号来分隔不同的运算。结果将在不同的行中返回。



```
echo '1+1; 2+2' | bc

```

### 精度


在某些计算中，bc 会使用精度的概念，即小数点后面的数字位数。默认的精度是 0。除法操作总是使用精度的设定。所以，如果你没有设置精度，有可能会带来意想不到的答案：



```
echo '3/2' | bc
echo 'scale=3; 3/2' | bc

```

乘法使用一个更复杂的精度选择机制：



```
echo '3*2' | bc
echo '3*2.0' | bc

```

同时，加法和减法的相关运算则与之相似：



```
echo '7-4.15' | bc

```

### 其他进制系统


bc 的另一个有用的功能是可以使用除了十进制以外的其他计数系统。例如，你可以轻松地做十六进制或二进制的数学运算。可以使用 `ibase` 和 `obase` 命令来分别设定输入和输出的进制系统。需要记住的是一旦你使用了 `ibase`，之后你输入的任何数字都将被认为是在新定义的进制系统中。


要做十六进制数到十进制数的转换或运算，你可以使用类似下面的命令。请注意大于 9 的十六进制数必须是大写的（A-F）：



```
echo 'ibase=16; A42F' | bc
echo 'ibase=16; 5F72+C39B' | bc

```

若要使得结果是十六进制数，则需要设定 `obase` ：



```
echo 'obase=16; ibase=16; 5F72+C39B' | bc

```

下面是一个小技巧。假如你在 shell 中做这些十六进制运算，怎样才能使得输入重新为十进制数呢？答案是使用 `ibase` 命令，但你必须设定它为在当前进制中与十进制中的 10 等价的值。例如，假如 `ibase` 被设定为十六进制，你需要输入：



```
ibase=A

```

一旦你执行了上面的命令，所有输入的数字都将是十进制的了，接着你便可以输入 `obase=10` 来重置输出的进制系统。


### 结论


上面所提到的只是 bc 所能做到的基础。它还允许你为某些复杂的运算和程序定义函数、变量和循环结构。你可以在你的系统中将这些程序保存为文本文件以便你在需要的时候使用。你还可以在网上找到更多的资源，它们提供了更多的例子以及额外的函数库。快乐地计算吧！




---


via: <https://fedoramagazine.org/bc-command-line-calculator/>


作者：[Paul W. Frields](https://fedoramagazine.org/author/pfrields/) 译者：[FSSlc](https://github.com/FSSlc) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
If you run a graphical desktop environment, you probably point and click your way to a calculator when you need one. The [Fedora Workstation](http://getfedora.org/workstation), for example, includes the [Calculator](https://wiki.gnome.org/Apps/Calculator) tool. It features several different operating modes that allow you to do, for example, complex math or financial calculations. But did you know the command line also offers a similar calculator called *bc*?

The *bc* utility gives you everything you expect from a scientific, financial, or even simple calculator. What’s more, it can be scripted from the command line if needed. This allows you to use it in shell scripts, in case you need to do more complex math.

Because *bc* is used by some other system software, like CUPS printing services, it’s probably installed on your Fedora system already. You can check with this command:

dnf list installed bc

If you don’t see it for some reason, you can install the package with this command:

sudo dnf install bc

## Doing simple math with bc

One way to use *bc* is to enter the calculator’s own shell. There you can run many calculations in a row. When you enter, the first thing that appears is a notice about the program:

$ 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'.

Now you can type in calculations or commands, one per line:

1+1

The calculator helpfully answers:

2

You can perform other commands here. You can use addition (+), subtraction (-), multiplication (*), division (/), parentheses, exponents (^), and so forth. Note that the calculator respects all expected conventions such as order of operations. Try these examples:

(4+7)*2 4+7*2

To exit, send the “end of input” signal with the key combination *Ctrl+D*.

Another way is to use the echo command to send calculations or commands. Here’s the calculator equivalent of “Hello, world,” using the shell’s pipe function (|) to send output from *echo* into *bc*:

echo '1+1' | bc

You can send more than one calculation using the shell pipe, with a semicolon to separate entries. The results are returned on separate lines.

echo '1+1; 2+2' | bc

## Scale

The *bc* calculator uses the concept of *scale*, or the number of digits after a decimal point, in some calculations. The default scale is 0. Division operations always use the scale setting. So if you don’t set scale, you may get unexpected answers:

echo '3/2' | bc echo 'scale=3; 3/2' | bc

Multiplication uses a more complex decision for scale:

echo '3*2' | bc echo '3*2.0' | bc

Meanwhile, addition and subtraction are more as expected:

echo '7-4.15' | bc

## Other base number systems

Another useful function is the ability to use number systems other than base-10 (decimal). For instance, you can easily do hexadecimal or binary math. Use the *ibase* and *obase* commands to set input and output base systems between base-2 and base-16. Remember that once you use *ibase*, any number you enter is expected to be in the new declared base.

To do hexadecimal to decimal conversions or math, you can use a command like this. Note the hexadecimal digits above 9 must be in uppercase (A-F):

echo 'ibase=16; A42F' | bc echo 'ibase=16; 5F72+C39B' | bc

To get results in hexadecimal, set the *obase* as well:

echo 'obase=16; ibase=16; 5F72+C39B' | bc

Here’s a trick, though. If you’re doing these calculations in the shell, how do you switch back to input in base-10? The answer is to use *ibase*, but you must set it to the equivalent of decimal number 10 in the **current** input base. For instance, if *ibase* was set to hexadecimal, enter:

ibase=A

Once you do this, all input numbers are now decimal again, so you can enter *obase=10* to reset the output base system.

## Conclusion

This is only the beginning of what *bc* can do. It also allows you to define functions, variables, and loops for complex calculations and programs. You can save these programs as text files on your system to run whenever you need. You can find numerous [resources on the web](http://phodd.net/gnu-bc/) that offer examples and additional function libraries. Happy calculating!

## Roberto

Why publicize a command line calculator in a time when the computer should read the mind of people and execute the operation ( i’m exceeding, I know ).

There are already, formidable and computational complex online tools that allow to do this, see wolfram.

Or very complex software like matlab even if not free.

What I perceive is that linux doesn’t have innovation to offer than a calculator and this is quite sad

Cit “Is this (is) the end my only friend”

## Sebastiaan Franken

Linux has more to offer than a GUI. Some people use it to work on and some of those people (I am one of those) have automated a great number of tasks, some of which include math. I don’t want my scripts to halfway stop and tell me “Hey, can you open the fancy calculator app you have and do some math for me? I’ll wait.”. No, I want my script to be able to do said math and just carry on and only tell me something when it’s done or when there’s an error. I use bc in a few scripts to calculate averages and do conversions from base-16 to base-10.

That way I can get more work done (in the same amount of time). Linux is all about choice and the freedom to choose the tool that works for you. Like I said, bc is a lifesaver to some of us

## Xose

Shorter:

bc <<< 1+1

## bluebat

A Command-line Calculator in pure BASH

http://www.slideshare.net/bluebat/a-commandlinecalculatorinpurebash

https://gist.github.com/bluebat/9760449

## Hiisi

Great and very useful post. Will apply in my work-flow. Thanks!

## Cătălin George Feștilă

new users can try more if you follow https://docs.fedoraproject.org/en-US/index.html

also the dnf is a great tool like yum the repo is the same …

## dhanvi

This is a very good article about bc 🙂

There is also a -l flag for bc which says to define the math lib, which also gives the answer in the decimal points

echo ‘ 3 / 5 ‘ | bc -l

## Elliot

An easier way to avoid issues with scale is to invoke bc with the -l (–mathlib) option.

## djf

Damn – that’s a great tip – thanks

bc -l <<< 5/450

instead of

bc <<< ‘scale=3;5/450’

## Paul W. Frields

@Elliot: Great tip, thanks!

## Brett

I love bc and use bc every day.

I have bc aliased to “bc -lq”. Sets a reasonable scale and drops the startup banner.

## Saman

Thank you so much. I’ve noticed “scale” doesn’t do the rounding. for example If I want to get the result of 3 / 4 using scale=1, the result is 0.7 instead of 0.8.

## Cătălin George Feștilă

! need time to follow the all docs …

## Brett

One thing I like to do when demonstrating bc is this:

2^4096

🙂

Brett

## Stan

Great info, I wasn’t aware of bc, learning something every day! Many thanks for the posting. I use the cli frequently and now don’t need to switch back to a gui for quick calculations ….. many thanks!

## hyhy123

Really great! I find this useful in some cases, especially when I am writing a shell script and find there are some simple math calculations. The bc can get things done perfectly!

## c4ifford

why not just use python?

## rpndude

Being a rpn person, I usually use ‘dc’; but ‘bc’ is great to, especially in scripts.

## Tad Marko

I’d recommend dc.

## Dale Raby

I never knew about this. I’ve been using an actual slide rule to do quick estimates for an “out the door price” for customers as it takes a few seconds to bring the GUI calculator up. As I always have a shell up, I can open bc and type 299.99+13+1.05(enter) and get $314.04. Yeah, I know I could invest a dollar and get a pocket calculator to replace the one that broke a couple months ago, but I always seem to “lose” those when they are on the counter and yeah, I know I could multiply by 10% and divide by two using my actual organic brain… but this is way cooler!

## Dale Raby

Hmmm… a problem manifests itself. You have to remember to hit the correct keys! 299.99+13*1.05

313.64

## Dale Raby

As I said, the CORRECT keys:

(299.99+13)*1.05

328.63

customers would probably prefer I forget about the brackets…

## Dale Raby

Ooops…

(299.99+13)*1.05

328.63

customers would probably prefer I forget about the brackets…