Santiago Lizardo - Technology entrepreneur

Arithmetics in Bash

Date Sun Sep 04 21:39:42 UTC 2011

Variable assignment in Bash is as easy as:

i=20 (without spaces around the = sign)

And you can refer to the previous variable with the dollar sign:

echo "Foo: $i"

But performing an simple math operation requires a no so intuitive syntax:

x=$(( $i + 13 ))

Take note: you need the dollar sign "$" and double parenthesis before "((" and after "))" the arithmetic operation.

Now a simple command to rename all files in the current folder to a new name with a counter in the name. (to generate unique names)

i=0; for file in *.txt; do mv $file step-$i.txt; i=$(($i+1)); done

Keep bashing!

Keywords: arithmetics, bash, operators

Powered by Google App Engine