bc command is used for command line calculator. It is similar to basic calculator by using which we can do basic mathematical calculations.
Arithmetic operations are the most basic in any kind of programming language. Linux or Unix operating system provides the bc command and expr command for doing arithmetic calculations. You can use these commands in bash or shell script also for evaluating arithmetic expressions.
Syntax:
bc [ -hlwsqv ] [long-options] [ file ... ]
Options:
-h, {- -help } : Print the usage and exit
-i, {- -interactive } : Force interactive mode
-l, {- -mathlib } : Define the standard math library
-w, {- -warn } : Give warnings for extensions to POSIX bc
-s, {- -standard } : Process exactly the POSIX bc language
-q, {- -quiet } : Do not print the normal GNU bc welcome
-v, {- -version } : Print the version number and copyright and quit
The bc command supports the following features:
- Arithmetic operators
- Increment or Decrement operators
- Assignment operators
- Comparison or Relational operators
- Logical or Boolean operators
- Math functions
- Conditional statements
- Iterative statements
1. Arithmetic Operators
Examples:
Input : $ echo "12+5" | bc
Output : 17
Input : $ echo "10^2" | bc
Output : 100
How to store the result of complete operation in variable?
Example:
Input:
$ x=`echo "12+5" | bc`
$ echo $x
Output:17
Explanation: Stores the result of first line of input in variable x and then display variable x as $x.
2. Assignment Operators
The list of assignments operators supported are:
- var = value : Assign the value to the variable
- var += value : similar to var = var + value
- var -= value : similar to var = var – value
- var *= value : similar to var = var * value
- var /= value : similar to var = var / value
- var ^= value : similar to var = var ^ value
- var %= value : similar to var = var % value
Examples:
Input: $ echo "var=10;var" | bc
Output: 10
Explanation: Assign 10 to the variable and print the value on the terminal.
Input: $ echo "var=10;var^=2;var" | bc
Output: 100
Explanation: Squares the value of the variable and print the value on the terminal.
How to store the result of complete operation in variable?
Example:
Input:
$ x=`echo "var=500;var%=7;var" | bc`
$ echo $x
Output:3
Explanation: Stores the result of 500 modulo 7 i.e. remainder of 500/7 in variable x and then display variable x as $x.
3. Increment Operators
There are 2 kinds of increment operators:
- ++var : Pre increment operator, variable is increased first and then result of variable is stored.
- var++ : Post increment operator, result of the variable is used first and then variable is incremented.
Examples:
Input: $ echo "var=10;++var" | bc
Output: 11
Explanation: Variable is increased first and then result of variable is stored.
Input: $ echo "var=10;var++" | bc
Output: 10
Explanation: Result of the variable is used first and then variable is incremented.
4. Decrement Operators
There are 2 kinds of decrement operators:
- – – var : Pre decrement operator, variable is decreased first and then result of variable is stored.
- var – – : Post decrement operator, result of the variable is used first and then variable is decremented.
Examples:
Input: $ echo "var=10;--var" | bc
Output: 9
Explanation: Variable is decreased first and then result of variable is stored.
Input: $ echo "var=10;var--" | bc
Output: 10
Explanation: Result of the variable is used first and then variable is decremented.
5. Comparison or Relational Operators
Relational operators are used to compare 2 numbers. If the comparison is true, then result is 1. Otherwise(false), returns 0. These operators are generally used in conditional statements like if.
The list of relational operators supported in bc command are shown below:
- expr1<expr2 : Result is 1 if expr1 is strictly less than expr2.
- expr1<=expr2 : Result is 1 if expr1 is less than or equal to expr2.
- expr1>expr2 : Result is 1 if expr1 is strictly greater than expr2.
- expr1>=expr2 : Result is 1 if expr1 is greater than or equal to expr2.
- expr1==expr2 : Result is 1 if expr1 is equal to expr2.
- expr1!=expr2 : Result is 1 if expr1 is not equal to expr2.
Examples:
Input: $ echo "10>5" | bc
Output: 1
Input: $ echo "1==2" | bc
Output: 0
6. Logical or Boolean Operators
Logical operators are mostly used in conditional statements. The result of the logical operators is either 1(TRUE) or 0(FALSE).
- expr1 && expr2 : Result is 1 if both expressions are non-zero.
- expr1 || expr2 : Result is 1 if either expression is non-zero.
- ! expr : Result is 1 if expr is 0.
Examples:
Input: $ echo "10 && 5" | bc
Output: 1
Input: $ echo "0 || 0" | bc
Output: 0
Input: $ echo "! 0" | bc
Output: 1
7. Mathematical Functions
The built-in math functions supported are :
- s (x): The sine of x, x is in radians.
- c (x) : The cosine of x, x is in radians.
- a (x) : The arctangent of x, arctangent returns radians.
- l (x) : The natural logarithm of x.
- e (x) : The exponential function of raising e to the value x.
- j (n,x) : The bessel function of integer order n of x.
- sqrt(x) : Square root of the number x. If the expression is negative, a run time error is generated.
In addition to the math functions, the following functions are also supported :
- length(x) : returns the number of digits in x.
- read() : Reads the number from the standard input.
- scale(expression) : The value of the scale function is the number of digits after the decimal point in the expression.
- ibase and obase define the conversion base for input and output numbers. The default for both input and output is base 10.
- last (an extension) is a variable that has the value of the last printed number.
Examples:
Input:
$ pi=`echo "h=10;4*a(1)" | bc -l`
$ echo $pi
Output: 3.14159265358979323844
Explanation: Assign the value of “pi” to the shell variable pi. Here, a refers to the arctangent function, which is part of the math library loaded with the -l option.
Input: $ echo "scale($pi)" | bc -l
Output: 20
Explanation: Gives the number of digits after decimal point in value of “pi” calculated in previous example.
Input: $ echo "s($pi/3)" | bc -l
Output: .86602540378443864675
Explanation: Gives sine values at “pi/3” angle. Angle must be in radians. Here, s refers to the sine function
Input: $ echo "c($pi/3)" | bc -l
Output: .50000000000000000001
Explanation: Gives cosine values at “pi/3” angle. Angle must be in radians. Here, c refers to the cosine function.
Input: $ echo "e(3)" | bc -l
Output:20.08553692318766774092
Explanation: Gives exponential^value as output.
Input: $ echo "l(e(1))" | bc -l
Output: .99999999999999999999
Explanation: Gives natural logarithm of the value i.e. w.r.t. base ‘e’.
Input: $ echo "obase=2;15" | bc -l
Output: 1111
Explanation: Convert Decimal to Binary.
Input: $ echo "obase=8;9" | bc -l
Output: 11
Explanation: Convert Decimal to Octal.
Input: $ echo "ibase=2;1111" | bc -l
Output: 15
Explanation: Convert Binary to Decimal.
Input: $ echo "ibase=2;obase=8;10" | bc -l
Output: 2
Explanation: Convert Binary to Octal.
8. Conditional Statements
Conditional Statements are used to take decisions and execute statements based on these decisions. bc command supports the if condition.
Syntax:
if(condition) {statements} else {statements}
Example:
Input: $ echo 'n=8;m=10;if(n>m) print "n is greater" else print "m is greater" ' | bc -l
Output: m is greater
9. Iterative statements
bc command supports the for loop and while loop for doing iterations.
Syntax:
for(assignment; condition; updation)
{
statements.....
.......
........
}
OR
while(condition)
{
statements.....
.......
........
}
Examples:
Input: $ echo "for(i=1; i<=10; i++) {i;}" | bc
Output:
1
2
3
4
5
6
7
8
9
10
Input: $ echo "i=1;while(i<=10) {i; i+=1}" | bc
Output:
1
2
3
4
5
6
7
8
9
10
Explanation: Both examples prints numbers from 1 to 10 using the respective looping syntax.
Some Pseudo Statements:
- break : This statement causes a forced exit of the most recent enclosing while statement or for statement.
- continue : The continue statement (an extension) causes the most recent enclosing for statement to start the next iteration.
- halt : The halt statement (an extension) is an executed statement that causes the bc processor to quit only when it is executed. For example, “if (0 == 1) halt” will not cause bc to terminate because the halt is not executed.
- return : Return the value 0 from a function. (See the section on functions).
- return(expression) : Return the value of the expression from a function. (See the section on functions). As an extension, the parenthesis are not required.
- limits : Print the local limits enforced by the local version of bc. (This is an extension).
- quit : When the quit statement is read, the bc processor is terminated, regardless of where the quit statement is found. For example, “if (0 == 1) quit” will cause bc to terminate.
- warranty : Print a warranty notice. (This is an extension).
10. Functions : Functions provide a method of defining a computation that can be executed later. Functions in bc always compute a value and return it to the caller. Function definitions are “dynamic” in the sense that a function is undefined until a definition is encountered in the input. That definition is then used until another definition function for the same name is encountered. The new definition then replaces the older definition.
Syntax:
define name (parameters)
{
statements.......
.......
........
return statement
}
11. We can write our arithmetic expressions in a file and then execute those statements by providing the filename to the bc command.
Example:
Input :
$ cat >> example.txt
2+5;
var = 10*3
var
print var
quit
Press ctrl+D
$ bc example.txt
Output :
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'.
7
30
TO AVOID SYSTEM GENERATED MESSAGE ON OUTPUT SCREEN, USE:
$ bc -q example.txt
Output :
7
30
12. Important Points:
- Bc command treats the semicolon (;) or newline as the statement separator.
- To group statements use the curly braces. Use with functions, if statement, for and while loops.
- If only an expression is specified as a statement, then bc command evaluates the expression and prints the result on the standard output.
- If an assignment operator is found. Bc command assigns the value to the variable and do not print the value on the terminal.
- A function should be defined before calling it. Always the function definition should appear first before the calling statements.
- If a standalone variable is found as a statement, bc command prints the value of the variable. You can also Use the print statement for displaying the list of values on the terminal.
https://youtu.be/_UwhS0IvwQk?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L
Similar Reads
arp command in Linux with examples
arp command manipulates the System's ARP cache. It also allows a complete dump of the ARP cache. ARP stands for Address Resolution Protocol. The primary function of this protocol is to resolve the IP address of a system to its mac address, and hence it works between level 2(Data link layer) and leve
2 min read
aspell command in Linux with examples
aspell command is used as a spell checker in Linux. Generally, it will scan the given files or anything from standard input then it check for misspellings. Finally, it allows the user to correct the words interactively. Spell checking is crucial when working with large documents, coding, or writing
3 min read
atd command in Linux with examples
atd is a job scheduler daemon that runs jobs scheduled for later execution. These jobs are one-time task(not recurring) at a specific time scheduled using 'at' or 'batch' utility. Syntax: atd [-l load_avg] [-b batch_interval] [-d] [-f] [-s] Options: -l : Specifies a limiting load factor, over which
2 min read
atrm command in Linux with examples
atrm command is used to remove the specified jobs. To remove a job, its job number is passed in the command. A user can only delete jobs that belong to him. Only superuser can delete any job even if that belongs to another user. Syntax: atrm [-V] job [job...] Options: -V : Used to print the version
1 min read
atq command in linux with examples
atq displays the list of pending jobs which are scheduled by the user. If the user is the superuser then the pending jobs of all the users will be displayed. The output lines display Job number, date, hour, queue, and username for each job. Syntax: atq [-V] [-q queue] Options: -V: It will display th
2 min read
autoconf command in Linux with examples
autoconf command is used in Linux to generate configuration scripts. Generate a configuration script from a TEMPLATE-FILE if given, or from âconfigure.acâ if present, or 'configure.in'. The output is sent to the standard output if TEMPLATE-FILE is given, otherwise, it is sent into âconfigureâ. To us
1 min read
autoheader command in Linux with Examples
autoheader command in Linux is used to create a template file of C â#defineâ or any other template header for configure to use. If the user will give autoheader an argument, it reads the standard input instead of reading configure.ac and also writes the header file to the standard output. This comma
3 min read
automake command in Linux with Examples
automake is a tool used for automatically generating Makefile.in files compliant with the set GNU Coding Standards. autoconf is required for the use of automake. automake manual can either be read on-line or downloaded in the PDF format. More formats are also offered for download or on-line reading.
1 min read
autoreconf command in Linux with examples
autoreconf is a Autotool which is used to create automatically buildable source code for Unix-like systems. Autotool is a common name for autoconf, automake, etc. These all together are termed as Autotools. Important Points: Provides Portability of source code packages by automatic buildable capabil
2 min read
AWK command in Unix/Linux with examples
Awk is a scripting language used for manipulating data and generating reports. The awk command programming language requires no compiling and allows the user to use variables, numeric functions, string functions, and logical operators. Awk is a utility that enables a programmer to write tiny but eff
8 min read