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"
fibash 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
MediumWrite a script that summarises test scores given as arguments.
- Open
scores.sh. Every argument is a whole-number score, and there is always at least one. - Add up all the scores in a variable called
total. - Count the scores of 50 or more in a variable called
passed, using((passed++)). - After the loop, print three lines:
Total: T, thenAverage: Awhere A is the total divided by the number of scores (a whole number, remainder dropped), thenPassed: P of N, where N is the number of scores. - Save the file.
Try it: run bash scores.sh 70 45 88. It prints:
Total: 203
Average: 67
Passed: 2 of 3Then 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 2Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground