NASutils Knowledge BaseUnofficialPolski

Bash · lesson 11 of 30 · Decisions and loopsCount with numbers

$(( )) counts whole numbers. awk counts fractions.

Programming on the NAS › Bash in 30 lessons

11-arithmetic.sh Download 11-arithmetic.sh

#!/usr/app/TurboShell/bin/bash
a=17
b=5
echo "17 + 5 = $((a + b))"
echo "17 / 5 = $((a / b)), the rest is $((a % b))"
echo "2 to the power of 10 = $((2 ** 10))"
((a++))
echo "a is now $a"

# Bash counts whole numbers only; awk counts fractions
bytes=8001563222016
awk -v b="$bytes" 'BEGIN { printf "%.1f GiB\n", b / 1024 / 1024 / 1024 }'
echo "in whole GiB: $((bytes / 1024 ** 3))"

Terminal

$ bash 11-arithmetic.sh
17 + 5 = 22
17 / 5 = 3, the rest is 2
2 to the power of 10 = 1024
a is now 18
7452.0 GiB
in whole GiB: 7452

Exercise

Turn 500 GB into GiB with two decimals.