Pages

Saturday, September 8, 2012

Calculations on Linux

Command Line calculator

how to perform standard calculations on the command line including addition, subtraction, multiplication, division, powers, square root, conversion.


From man pages

bc - An arbitrary precision calculator language




Addition, subtraction, multiplication and division


 $ echo '1+2' | bc    
  3    
 $ echo '5-3' | bc    
  2  
 $ echo '3*4' | bc    
  12    
 $ echo '9/2' | bc    
  4    


setting decimal places 

 $ echo 'scale=4;9/2' | bc   
  4.5000   


Square root

 $ echo 'scale=4;sqrt(25)' | bc   
  5.0000   


Conversion

converting decimal to hex
 $ echo 'obase=16;128' | bc   
  80   
 $ echo 'obase=16;255' | bc   
  FF   


converting decimal to binary
$ echo 'obase=2;255' | bc   
  11111111   

converting binary to decimal
 $ echo 'ibase=2;obase=A;0110' | bc   
  6   


converting hex to decimal
 $ echo 'ibase=16;obase=A;FF' | bc   
  255   


bc with shell scripts

 $ VAR=6 ; echo "$VAR^2" | bc  
 36  



Linux Date command


 $ date  
 Sat Sep 8 09:53:55 EEST 2012  
 $ date --date="1 year ago" +%Y%m%d-%H%M  
 20110908-0953  
 $ date --date="4 months ago" +%Y%m%d-%H%M  
 20120508-0954  
 $ date --date="100 days ago" +%Y%m%d-%H%M  
 20120531-0954  
 $ date --date="10 hours ago" +%Y%m%d-%H%M  
 20120907-2354  
 $ date --date="15 minutes ago" +%Y%m%d-%H%M  
 20120908-0939  
 $ date --date="1 year ago 15 minutes ago" +%Y%m%d-%H%M  
 20110908-0940  

No comments: