Variables and arithmetic

Assign without spaces, use $((...)) for integer arithmetic, capture output with $(...), and give defaults with ${var:-default}.

Runs in Zerethon IDE · Bash 5.2 Official Bash documentation ↗
main.sh
count=3
name="Ada Lovelace"
readonly limit=10

echo "$count $name $limit"
echo $((count * 2)) $((7 / 2)) $((7 % 2)) $((2 ** 10))
(( count += 1 ))
echo "count is now $count"

report="report-$((count + 1)).txt"
echo "$report"
lines=$(printf '%s\n' a b c | wc -l)
echo "lines: $lines"
echo "${missing:-default} ${#name}"

Output

3 Ada Lovelace 10
6 3 1 1024
count is now 4
report-5.txt
lines: 3
default 12
  • No spaces around =: count=3. count = 3 runs a command named count.
  • Bash arithmetic is whole numbers only: $((7 / 2)) is 3. For decimals use awk (see “Pipes and tools”).
  • $(command) is replaced by the command's output, without the final newline.
  • ${var:-default} uses the default when var is unset or empty; ${#var} is the length.

Watch out: A number with a leading zero is octal in arithmetic: $((08)) fails with value too great for base. Strip zeros first, or write $((10#08)).