BASH math and formatting

BASH math and formatting

Here are some things that I don't use often enough to memorize yet seem to be looking-up every few months.

Formatting a number

To force a number to be base-10 and space-pad it to five places:

printf "\nLinks copied\t\t%5d\n" $(( 10#$copyCount ))

Use “%05d” to zero-pad the number.

Arithmetic

To increment a counter – several methods, take note where the variable is and is not prefixed with a dollar-sign:

(( z += 1 ))
((z++))
z=$(($z+1))
z=$((z+1))
let z=z+1
z=`expr $z + 1`

Modulo

a=`expr 5 % 3`

Tests

Comparison

b=`expr $a \> 10`
b=`expr $a \<= 10`
b=`expr $a = $c`

Check if a string is an integer

function is_integer() {
  [ "$1" -eq "$1" ] > /dev/null 2>&1
  return $?
}

if is_integer $MyVar
then
  echo "It's an integer"
fi

Strings

Length of a string

b=`expr length $a`
b=${#a}