Menu
CoddyTech

Arithmetic

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 8 of 39.

Bash does whole-number math inside $(( )), with +, -, *, / and %. Division drops the remainder, so $(( 17 / 5 )) is 3, and % gives that remainder: $(( 17 % 5 )) is 2. Inside the parentheses a variable needs no $.

(( )) without the $ is a condition: (( mins > 120 )) is true when mins is more than 120, written with > instead of -gt.

#!/bin/bash
mins=$1
echo "$(( mins / 60 )) h $(( mins % 60 )) min"
if (( mins > 120 )); then
  echo "Long film"
fi

bash film.sh 135 prints 2 h 15 min, then Long film. bash film.sh 95 prints only 1 h 35 min.

((count++)) adds one to count, which makes counting in a loop short:

count=0
for f in "$@"; do
  ((count++))
done
echo "$count files"

Without $(( )), x=$x+1 stores the text 5+1, not 6.

challenge icon

Challenge

Medium

Write a script that summarises test scores given as arguments.

  1. Open scores.sh. Every argument is a whole-number score, and there is always at least one.
  2. Add up all the scores in a variable called total.
  3. Count the scores of 50 or more in a variable called passed, using ((passed++)).
  4. After the loop, print three lines: Total: T, then Average: A where A is the total divided by the number of scores (a whole number, remainder dropped), then Passed: P of N, where N is the number of scores.
  5. Save the file.

Try it: run bash scores.sh 70 45 88. It prints:

Total: 203
Average: 67
Passed: 2 of 3

Then run bash scores.sh 50 49. A score of exactly 50 passes, and 99 divided by 2 gives 49:

Total: 99
Average: 49
Passed: 1 of 2

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground