This is a brief article describing different techniques employed for performing arithmetic operations on the command line.
Using expr:
Using the expr built in is a common way of evaluating arithmetic expressions. Here is an example:
[root@cclient1 ~]# v=10; x=1; expr $v + $x
11
Using let:
Let is another bash built in that can be used for performing arithmetic operations on the command line. Here are a couple of examples:
[root@cclient1 ~]# s=10; let "s+=10"; echo $s
20
s=10; echo $(($s+10))
20
Using expr:
Using the expr built in is a common way of evaluating arithmetic expressions. Here is an example:
[root@cclient1 ~]# v=10; x=1; expr $v + $x
11
Using let:
Let is another bash built in that can be used for performing arithmetic operations on the command line. Here are a couple of examples:
[root@cclient1 ~]# s=10; let "s+=10"; echo $s
20
s=10; echo $(($s+10))
20
Both expr & let are easy to use but their drawback is that they can't handle floating point expressions.
For that we have two more commands coming in the picture viz bc & awk.
Using bc:
Invoking bc directly from the command line isn't very useful in a script as we'll usually want the script to be non-interactive. So, here are a few examples of feeding input arithmetic expressions to bc to evaluate:
[root@cclient1 ~]# a=10;b=15; echo "scale=4 ; $a/$b" | bc
.6666
[root@cclient1 ~]# a=10;b=15; bc <<< "scale=2; $a/$b"
.66
[root@cclient1 ~]# a=100;b=70; echo "$a/$b" | bc -l
1.42857142857142857142
The scale represents the level of precision we want after the floating point. The "-l" options specifies maximum precision possible.
Using awk:
Awk can be used for performing arithmetic operations on it's own as well as on fields extracted from a file.
An example of awk standalone arithmetic usage:
[root@cclient1 ~]# a=10;b=7; awk "BEGIN {print $a / $b}"
1.42857
If you use the usual ' commas that we're used for enclosing awk expressions then it'll return an error since under ' ' the $ signs get interpreted literally. The BEGIN keyword specifies one time execution.
An example of awk extracting fields from a column & summing the results:
[root@cclient1 ~]# cat file | awk '{ print $1}'
15
8
10
17
26
[root@cclient1 ~]# awk '{ sum += $1} END { print sum}' file
76
No comments:
Post a Comment