01Understanding bc
bc (which stands for "basic calculator") is a language that supports arbitrary precision numbers and interactive execution of statements, and comes pre-installed on macOS and most Unix-like systems. bc is often used as either a simple, interactive calculator or a processing language in shell scripts. To verify whether it's installed on your system, you can type bc --version into your terminal and hit Enter. This command will display bc's version.
02Performing basic arithmetic
Let's start by performing some basic calculations. In your terminal, type bc, and hit Enter. This will start bc in interactive mode. Now you can type a mathematical expression directly into the terminal, like this:
$ 3 + 7After hitting Enter, bc will evaluate the expression and display the result (10 in this case).
03Using mathematical operations
bc supports a variety of mathematical operations. Here are a few examples:
- Addition:
5 + 3 - Subtraction:
7 - 2 - Multiplication:
3 * 4 - Division:
10 / 2 - Exponentiation:
2^3(this will calculate 2 to the power of 3)
Simply type the expressions as shown above and hit Enter to evaluate them.
04Setting scale for decimal division
By default, bc performs integer division. If you divide 10 / 3, you will get 3 instead of 3.33333. To perform decimal division, you need to set the scale. The scale defines the number of decimal points bc will consider while dividing.
Type scale=5 and hit Enter to set the scale to 5 decimal places. Now, if you divide 10 / 3, you'll get 3.33333.
05Exiting bc
To exit bc and return to your standard terminal prompt, simply type quit and hit Enter, or use the Ctrl+D shortcut.
06Using bc in shell scripts
Aside from interactive use, bc can be used in shell scripts for performing calculations. For instance, you can use the following command to calculate the area of a circle with a radius of 5 (using the formula πr^2):
$ echo "scale=2; 3.14159 * 5^2" | bcThis will display 78.53, the area of the circle.
Well done! You've turned your terminal into a powerful calculator and levelled up your command-line game. As we draw closer to the evening, we've unlocked another facet of terminal power. Stay tuned as we continue our 24-hour journey through terminal land, leaving no GUI app unchallenged.
Remember, this is one part of our series aimed at replacing 24 GUI applications with terminal commands. Our day began at 6 am, and at 4 pm, we're still going strong!