The “dc” Command in Linux [15+ Practical Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The dc command in Linux is a flexible CLI calculator for arithmetic operations that makes effective use of reverse-polish notation (RPN), a mathematical notation where every operator follows all of its operands. This means that users enter numbers first, then operators and the calculator processes them in last-in-first-out order.

This ‘desktop calculator’ is widely accessible due to its cross-platform availability on multiple Linux versions, Mac OS X, and Windows. It is frequently used in scripts and terminal sessions to show system statistics and perform exact numerical operations.

Syntax of “dc” Command

The syntax of the dc command typically follows the following format:

dc [option] [expression] / [file]

Note: The element enclosed by a square bracket in the above syntax is not mandatory.

EXPLANATION

Here,

  • dc: Command itself which stands for desk-calculator.
  • [option]: Optional flags or parameters that modify the behavior of the dc command. Common options include -e for executing expressions directly and -f for reading commands from a file.
  • [expression] / [file]: If you use the -e option, you should provide your desired expression or if you use the -f option, you should provide the file name that contains desired expressions.

Options of “dc” Command

There are several types of options associated with the dc command in Linux. Here, I will briefly discuss some of the most used options. To learn about all the options of the dc command from its manual page, just execute the following command on your terminal:

man dc

Option Types Options Purpose
General

 

-V or –version Displays version information of dc command.
-h or –help Displays a brief help message for dc command mentioning general options and their functions.
-e or –expression Executes the provided expression using dc calculator.
-f or –file Reads and executes commands from the specified file using dc calculator.
Printing Commands

 

p Prints the top element of the stack in the dc calculator.
n Prints the value on the top of the stack, popes it off, and does not print a new line after.
f Prints the entire stack of elements in a list.
Arithmetic

 

+ Pops out 2 numerical values from the top of the stack, adds them, and pushes the result on top of the stack.
Pops out 2 values, subtracts the first value from the second value, and pushes the result on top of the stack.
* Pops out 2 numerical values from the top of the stack, multiplies them, and pushes the result on top of the stack.
/ Pops out 2 values, divides the second one by the first one in the stack, and pushes the result on top of the stack.
% Pops out 2 values, does the same operation as the “/” operator, and outputs the remainder (instead of the quotient) on top of the stack.
^ Pops out 2 values, takes the first value (non-factional) as the exponent and the second value as the base, and pushes the result on top of the stack.
v Pops out 1 value from the list, square roots it, and pushes the value on top of the stack.
Stack Control c Clears the whole stack.
d Duplicates the top value of the stack, creating an additional copy of it. For instance, “4d*p” calculates the square of 4 and displays the result.
r Swaps the positions of the top two values on the stack, reversing their order.
Register

 

sr Removes the value from the top of the stack and saves it into register r.
lr Copies the value stored in register r and adds it to the stack. This action doesn’t change the content of register r.
Parameter

 

i Removes the value from the top of the stack and uses it to determine the input radix.
o Removes the value from the top of the stack and uses it to determine the output radix.
k Removes the value from the top of the stack and uses it to determine the precision value.
String [characters] Creates a string composed of characters (in between [ ]) and places it onto the stack.
a If the top item on the list is a number, it is removed from the stack. Again if it is a string, it is removed and the first character of the string is pushed up.
x Removes a value from the stack, treats it as a macro, executes it, and then places the result back onto the stack.
>r Compares the first 2 values of the list. If the topmost value is greater, the value of the register is printed.
<r Compares the first 2 values of the list. If the topmost value is less, the value of the register is printed.
!>r Compares the first 2 values of the list. If the topmost value is not greater than the 2nd value, the value of the register is printed.
!<r Compares the first 2 values of the list. If the topmost value is not less than the 2nd value, the value of the register is printed.
=r Compares the first 2 values of the list. If the topmost value is exactly equal to the 2nd value, the value of the register is printed.
!=r Compares the first 2 values of the list. If the topmost value is not equal to the 2nd value, the value of the register is printed.
q Exits the dc calculator.
Status Inquiry

 

Z Pops a value from the stack, counts its digits (excluding leading zeros for numbers), and pushes the count back onto the stack.
X Removes a value from the stack, determines the number of fractional digits it contains, and then adds that number onto the stack. If the value is a string, it pushes 0 instead.
z Calculates the number of objects on the list and pushes the value on top.

Practical Examples Using “dc” Command in Linux

Below, I’ll outline a handful of practical applications and examples using the dc command so that you can gain a deeper understanding of this topic and learn to use the dc calculator in Linux more effectively:

1. Reading from Expression and File

You can use the -e option and -f option of the dc command to execute a script directly and a script from a file respectively. For example, to execute a script directly to add two numbers and print the result, use the following command:

dc -e '10 20 + p'

To execute a script from a file named script_file.dc, execute the below command:

dc -f script_file.dc

dc -e and dc -f command

2. Printing Topmost Element from Stack

To work with the dc command in Linux, first, you just need to type dc and press ENTER inside the terminal. Then you will enter the dc calculator mode of the terminal and you do not need to write dc over again while writing a new line. Next, enter numbers separated by spaces or newlines. After entering numbers, you can perform any arithmetic operations on them. Also remember that dc uses a stack-based system. Each number or operation you input pushes or pops values from the stack.

To print the topmost item from the list, run the following command after entering the dc calculator:

10 11 12 p

p Output option for dc command in Linux

Here the topmost element is the element you entered last inside the stack. In this case, it is 12.

Note: Here, the topmost element is not removed and only being displayed inside the terminal. But, if you want to display the topmost element as well as delete it from the stack, you can run the following command instead: 10 11 12 n.

3. Printing The Whole Stack

To print all the elements from the stack, run the following command:

10 11 12 f

f Output option for dc command in Linux

See from the image, all the stack elements are displayed (each in a new line with Last-in-First-out order).

4. How to Do Arithmetic Operations Using “dc” Command?

Arithmetic options are the most important options to learn for doing any calculation. Below I have demonstrated their functionalities through practical scenarios:

i. Addition

To add 2 numeric values run the following command:

10 11 + p

To add more than 2 values run the following command:

10 11 12 + + p

Adding 2 or more values

See from the above image, in the second command, the 3rd value is added to the summation of the 1st 2 values. In this way, if you need to add n number of items you need to put (n-1) number of “+” signs after the values. Additionally, with the help of the f command, you can see that the new values are stacked on top of the old values.

ii. Subtraction

To subtract the top value from the 2nd value of the stack, run the following command:

12 10 - p

Subtracting numeric values

For incorporating multiple values in the subtracting operation follow the same procedure as addition.

iii. Multiplication

To multiply values from the top of the stack, run the following command:

10 12 * p

Multiplying Numeric Values

For multiplying more than 2 values together, follow the same procedure as addition.

iv. Division

The precision value in the dc calculator determines the number of digits displayed after the decimal point. To divide the 2nd value by the top value of the stack and set a precision value of 2, run the following command:

2 k 12 10 / p

Dividing values and setting precision

Here, to set the precision value to 2, I wrote 2 followed by the k command before writing the numbers and operator for division. And if you do not set the precision value, the division results in 1 which is incorrect. The reason behind this is that if you do not fix the precision value yourself, it is set to 0 by default.

v. Calculating Modulus (Remainder)

To calculate the remainder after a division operation, run the following command:

12 10 % p

Calculating the remainder

In the above image, the output is 2. Because, if you divide 12 by 10, the quotient is 1 and the remainder is 2.

vi. Calculating Exponential

To calculate an exponential where the topmost value of the stack is the exponent and the 2nd value is the base, run the following command:

2 3 ^ p

Calculating Exponents

Note: You can not enter a fractional number as the exponent value.

vii. Calculating Square Root

Like the division operation, you also need to set the precision value before calculating the square root of a number. Because if the number is not a perfect square, the result of the square root would obviously result in a fractional number.

To calculate the square root of the top value from the stack and set the precision value to 2, run the following command:

2 k 8 v p

Calculating square root

If you do not set the precision value accordingly, you could end up getting an incomplete as well as a wrong answer.

Note: If you set the precision value once, you do not need to set the value each time you do a calculation, given that you do not quite the dc calculator after setting the value.

5. Clearing a Stack

To clear the entire stack to begin new calculations just type c on the dc calculator terminal and press ENTER:

Clearing entire stack for dc command in Linux

6. Swapping Position in Stack

To swap the positions of the top 2 contents of the stack just type r inside the dc calculator terminal and press ENTER. For example, run the following command:

2 3 4 r f

Reversing stack objects for dc command in Linux

In the above image, the numbers 2, 3, and 4 are added to the stack with 4 being the topmost number and 2 being the bottom number. The r command swaps the top 2 values in output that are 4 and 3 and the f command displays the swapped stack.

7. Storing Stack Value into Register

To pop off the top value from the stack and store it inside the register r, run the following command:

2 3 4 sr

Storing stack value for dc command in Linux

In the above image, you can see that the topmost value of the stack is not inside the stack anymore. Rather, it has been stored in a register named r.

8. Parse Value from Register

To copy and paste the stored value that you stored before, just type lrp and press ENTER. For instance, run the following command:

lrp

Copying register value

In the above image, after storing the top object of the stack in register r, lr copies that value, and p outputs it.

9. Use Input Numbers in Binary Format

To fix the input radix (number base) for dc command in Linux, type the value of the base followed by i. For example, to fix the input radix into binary (base 2), run the following command:

2 i 10 11 +

Fixing Input Radix

In the above image, the input radix is set to binary by typing 2 followed by the command i. That is why, when I input the numbers 10 and 11, they were considered binary values that correspond to numbers 2 and 3 respectively in the decimal system. Thus, I got 5 as the output value for the addition of 2 & 3.

Note: By changing the base value before i, you can also set the input radix to an octal (8) or hexadecimal (16) number.

10. Use Output Number in Binary Format

To fix the output radix, type the value of the base followed by o. For example, to fix the output radix into binary (base 2), run the following command:

2 o 15 16 + p

Fixing Output Radix

In the above image, the output of the addition in decimal is 31. But 31 in decimal is equivalent to 11111 in binary.

Note: By changing the base value before o, you can also set the output radix to octal (8) or hexadecimal (16) number.

11. Set Precision for Output

To fix the precision value (number of places after the decimal point) of the calculator, type the precision value followed by k. For example, if you want to set the precision value to 3, and get the result of a mathematical operation accordingly, run the following command:

3 k 100 30 / p

Fixing precision value

The output for the division is 3.333, printed up to 3 numbers after the decimal point as I set in the command.

12. Push Non-numeric Values in Stack

To accumulate a string inside the stack of the dc calculator, we just need to write the string inside the third bracket ([ ]):

Adding string to stack

13. Executing Macro from Expression

A macro is a sequence of instructions or commands grouped as a single command. In the context of the dc command in Linux, a macro is a set of operations enclosed within square brackets […]. It allows you to define custom operations or calculations and execute them as a single command.

For example, [ 1 1 + ] defines a macro that adds two numbers together. When you write [ 1 1 + ]x, you are executing this macro, which adds 1 and 1 together, and it adds the result to the stack. For instance:

[ 1 1 +]x  4 5 f

Executing macro from expression

In the image above, [1 1 +]x does the addition and then appends the result that is 2 with other values in the stack. You can check that with the help of the f option.

14. Comparing Numbers & Generating Conditional Output

You can compare 2 numeric values and set up a conditional output system based on that comparison. For example, look at the image below:

Comparison operators

OUTPUT ANALYSIS

In the above image, at first, I stored the value 4 in register r by using the sr command. Then, I showed the functions of comparison operators one by one. If the comparison is true, the calculator returns the value of the register. On the contrary, if the comparison becomes false, the calculator returns “dc: stack empty” instead of the register value. For instance: the 1 2!=r p command prints the value of the register r as 1 is not equal to 2 and the condition becomes true.

Command c clears the stack after every operation and command p prints the conditional output based on the comparison. However, the value that is stored inside the register r remains unchanged. Lastly, when I write q and press ENTER, it makes the terminal exit the dc calculator mode.

15. Counting Number of Digits in a Number

To count the digit numbers of a number and push the result on top of the stack, just type Z and press ENTER. Suppose, the top element inside the stack is “14”. Then, if you type Z and press ENTER, the number will be replaced with the count of its digit numbers which is 2. Later, you can use the f command to display the final stack and check it.

Counting number of digits

Here, the command replaces the number 14 with its digit number, which is 2.

Note: To count the number of fractional digits of the top number in the stack, just type X and press ENTER. For example, if the top number is 14.812, the command will replace it with its number of fractional digits which is 3. But if the top element of the stack is a string, this will replace it with the value 0.

16. Calculating the Size of a Stack

If you want to count the number of elements inside the stack and push the result on top of the stack, just write z and press ENTER:

Counting number of stack element

In the image, you can see that the number of elements on the stack was previously 4, and the command pushed this number on top of the stack, making the current number of elements 5.

Conclusion

In this article, we have explored the capabilities of the dc command in Linux through various practical examples revealing its flexibility and convenience for arithmetic calculations. While dc provides powerful arithmetic functionalities, I encourage the users to further explore this command along with its alternative tools for more advanced mathematical operations or specialized requirements. Thank you.

People Also Ask

What is the dc command in Linux?

The dc command in Linux is a calculator that uses reverse-polish notation (RPN) for performing arithmetic operations. It’s like a fancy calculator that helps you work with numbers in a different way.

What is an RPN calculator?

An RPN (Reverse Polish Notation) calculator is a type of calculator that represents mathematical expressions in a postfix notation, where operators follow their operands.

This means that users enter numbers first, then operators, and the calculator processes them in last-in-first-out order. Unlike algebraic calculators, which use parentheses to prescribe the order of operations, RPN calculators do not require such symbols. It requires fewer keystrokes and thus generates a lower risk of errors, particularly in complex calculations, where you do not need to handle parenthesis or track nested expressions. Lastly, RPN’s stack-based logic is compatible with human thought processes, which makes it intuitive for many users once they become used to it.

How does the dc command differ from the bc command?

The dc command differs from the bc command in a way that is, dc operates on a Reverse-Polish Notation (RPN) format, focusing on simplicity and integer arithmetic by default, while bc employs an algebraic Notation, facilitating floating-point arithmetic and offering advanced features like variables, functions, and loops.

How to add the first letter of a string to the stack?

To add the first letter of a string to the stack, type “a” inside the dc calculator terminal. This action removes the topmost string but leaves the position filled with the first letter of that string. For example: If the topmost content of the stack is “fourteen”, typing “a” would replace it with its first character, which is f.  If the top element of the stack is a number, typing “a” would remove that number from the stack and leave the position empty.

How to duplicate a stack value?

To duplicate the topmost value of the stack just type d inside the dc calculator terminal and press ENTER. The duplicate value will enter the stack as the topmost element and then, you can use this duplicate value in a calculation. For instance, if you run the command 4d*p inside the terminal, you will get the square of the number 4 as the topmost value of the stack is 4.

How to open a calculator in Linux using command line?

To open a calculator in Linux using the command line, you can use the calc command followed by the arithmetic expression you want to calculate. For example: calc 5 + 3. This command will open the calculator and compute the expression “5 + 3”, displaying the result in the terminal. If the calc command is not installed by default on your system, you may need to install it from your distribution’s package repository.

How do you count the number of characters in a variable in Linux?

To count characters in a variable, use “wc -c” for character count and the -n option with echo to omit newline characters. For that, use the code, echo -n "$variable" | wc -c .

Rate this post
Avatar photo

Md. Nafis Soumik graduated from the Bangladesh University of Engineering & Technology, Dhaka, with a BSc—Engg in Naval Architecture & Marine Engineering. In January 2023, Soumik joined Softeko as an Excel and VBA content developer. Since then, he has authored over 50 articles, spanning topics from fundamental to advanced Excel concepts such as Data Analysis and Manipulation, Data Visualization, Pivot Tables, Power Query, VBA, and so on. He participated in 2 specialized training programs on VBA and Chart & Dashboard design in Excel. Furthermore, he possesses a keen interest in Linux and currently serves as an executive content developer specializing in Linux. He aims to produce valuable content tailored to Linux users. During his leisure time, he enjoys music, traveling, and science documentaries. Read Full Bio

Leave a Comment