Shell script numerical calculation bc command

bc command

-Handle numerical values with arbitrary precision (specify the number of digits after the decimal point) and calculate various mathematical functions such as four arithmetic operations, square roots, and trigonometric functions.

[Premise] The bc command cannot be used unless it is installed, so install it with the following command.

$bc


$ sudo yum install bc

Simple calculation

Calculate by passing the calculation content as a character string to the bc command using |.

Addition (eg


[hkoen@localhost ~]$ echo "20.5+5" | bc
25.5

Division (eg


[hkoen@localhost ~]$ echo "20.5/5" | bc
4

Complex calculations

Use -l to load a standard math library and perform more complex math functions

Square root (eg


[hkoen@localhost ~]$ echo "scale=20;sqrt(20.5/5)" | bc -l
2.02484567313165869332

The above means that the calculation result of √ (20.5 / 5) is displayed to the 20th decimal place.

Try writing with a shell script

Describe it in a shell script file called base10.sh (optional).

base10.sh file contents


#!/bin/bash

echo "20.5+5" | bc
echo "20.5*5" | bc
echo "scale=10;sqrt(2)" | bc -l
echo "$1 + $2" | bc     #Argument 1,Set argument 2

base10.sh file execution result


[hkoen@localhost ~]$ chmod 755 base10.sh
[hkoen@localhost ~]$ ./base10.sh 7 9
25.5
102.5
1.4142135623
16

First, give the user execute permission for the file with chmod 755 base10.sh.

Then, after calling ./bas10.sh, specify argument 1, argument 2: 7, and 9 and execute.

It calculates normally.

Recommended Posts

Shell script numerical calculation bc command
Shell script command replacement
[Infrastructure] Linux command, shell script collection
Shell script basics # 2
Linux [shell command]
Shell script special variables
Shell script @ study memo
Numerical calculation with Python
Let's try a shell script
Until the shell finds the command