Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SHELL

bash arithmetics

# Basic arithmetic using let
let a=5+4
echo $a # 9
let "a = 4 * 5"
echo $a # 20
let a=4*5 # No spaces, Skip the asterisk '*'
echo $a # 20
let a++
echo $a # 21

# Basic arithmetic using expr
a=$( expr 10 - 3 )
echo $a # 7
expr 5 + 4 #9
expr "5 + 4" #5 + 4, Strings are not evaluated
expr 5+4 #5+4, Spaces are required
expr 5 * 2 #10
expr ( 11 % 2 ) + 5 #6, parenthesis must be escaped

# Basic arithmetic using double parentheses
a=$(( 3 * 3 ))
echo $a # 9
b=$(( a + 4 ))
echo $b # 12
b=$(( $a + 4 ))
echo $b # 12
(( b++ ))
echo $b # 13
(( b += 3 ))
echo $b # 16

# Show the length of a variable.
a='Hello World'
echo ${#a} # 11
b=4953
echo ${#b} # 4
 
PREVIOUS NEXT
Tagged: #bash #arithmetics
ADD COMMENT
Topic
Name
3+1 =