Student Reviews
( 5 Of 5 )
1 review
Video of Bash Shell Scripting For Beginners - How to do Math in Bash in Bash Scripting course by Mental Outlaw channel, video No. 8 free certified online
In this video I discuss how to do math in bash both with the echo command and the expr command, I also briefly discuss how to format floating point numbers in bash to a specific decimal place.
Source code in this video
#this will echo the literal string
echo 1 + 1
##you need to use expr instead of echo to get the proper output
expr 1 + 1
expr 3 - 2
#you can create variables that equal the result of the calculation this way
add_result$(expr 20 + 8)
sub_result$(expr 20 - 8)
#escape the with a backslash (\) otherwise you'll get a syntax error here.
mul_result$(expr 20 \ 8)
div_result$(expr 20 / 5)
rem_result$(expr 20 % 5)
echo '$add_result is equal to '$add_result
echo '$sub_result is equal to '$sub_result
echo '$mul_result is equal to '$mul_result
echo '$div_result is equal to '$div_result
echo '$rem_result is equal to '$rem_result
num150
num210
# escaping is not necessary when using echo
echo $(( num1 + num2 ))
echo $(( num1 - num2 ))
echo $(( num1 num2 ))
echo $(( num1 / num2 ))
echo $(( num1 % num2 ))
#floating point numbers
#by default bash cannot do math with decinam numbers, atleast not using expr or echo
expr 20 + 0.5
#to avoid errors pipe results into bc, which stands for basic calculator
echo "20.5 + 0.4" bc
#this will not give you the proper output because it cuts off the decimal
echo "20.5 / 5" bc
#To get past this error we must use the -l command after bc
echo "20.5 / 5" bc -l
#use scale to round to a particular decimal place
echo "scale3;20.5 / 5" bc -l
End of Source Code
Subscribe to my YouTube channel http://goo.gl/9U10Wz
and be sure to click that notification bell so you know when new videos are released. ₿ Help Support the Channel by Donating Crypto ₿
Bitcoin
3MMKHXPQrGHEsmdHaAGD59FWhKFGeUsAxV
Ethereum
0xeA4DA3F9BAb091Eb86921CA6E41712438f4E5079
Litecoin
MBfrxLJMuw26hbVi2MjCVDFkkExz8rYvUF
Dash
Xh9PXPEy5RoLJgFDGYCDjrbXdjshMaYerz
Zcash
t1aWtU5SBpxuUWBSwDKy4gTkT2T1ZwtFvrr
Chainlink
0x0f7f21D267d2C9dbae17fd8c20012eFEA3678F14
Bitcoin Cash
qz2st00dtu9e79zrq5wshsgaxsjw299n7c69th8ryp
Etherum Classic
0xeA641e59913960f578ad39A6B4d02051A5556BfC
USD Coin
0x0B045f743A693b225630862a3464B52fefE79FdB