9/12/2013

Bash Shell Math

While the bash shell can only do integer arithmetic, it can do it in several ways:
Double Parenthesis, Dollar Square Brackets. the let statement, and command substitution of expr which was used to arithmetic in the original Bourne Shell, sh.

Double Parenthesis

x=$(( 5 * 3 )) ; echo $x
15

y=$(( $x / 4)) ; echo $y
y=$(( x / 4)) ; echo $y # dollar is optionaly
# Floor division rounds down always

Increments/Decrements
y=0
((y++)) ; echo $y
1
((y--)) ; echo $y
0
((++y)) ; echo $y
1
((--y)) ; echo $y
0
((y+=2)) ; echo $y
2
((y-=2)); echo $y
0

Different Base Numbers
x=$((2#0101)) ; 
echo $x
5
x=$((16#ff)) ; echo $x
255
Also:
echo $((0xff)) # hexadecimal
255
echo $((0Xff)) # hexadecimal
255
echo $((077)) # octal
63


Dollar Square Brackets

x = 0
x = $[ $x + 1 ]
echo $x
1

let Statement

The let statement is special in that expressions can dereference the value of a variable without using the dollar symbol. For example,
ec
let x=3
let y=4 + x
echo $y
7

expr Command Substitution

x=`expr 3 + 4`
echo $x
7



1 comment:

Tricia said...

I love you for that!

About Me - WrightRocket

My photo

I've worked with computers for over 30 years, programming, administering, using and building them from scratch.

I'm an instructor for technical computer courses, an editor and developer of training manuals, and an Android developer.