Bash · lesson 12 of 30 · Decisions and loopsWrite functions
A function reads $1, keeps its names local and gives text back through its output.
12-functions.sh Download 12-functions.sh
#!/usr/app/TurboShell/bin/bash
title() {
echo "$1"
echo "${1//?/-}"
}
# A function gives text back through its output
human() {
local bytes=$1 unit=0
local -a units=(B KiB MiB GiB TiB)
while ((bytes >= 1024 && unit < 4)); do
bytes=$((bytes / 1024))
unit=$((unit + 1))
done
echo "$bytes ${units[unit]}"
}
title "Sizes"
human 900
size=$(human 52428800)
echo "the second file has $size"
Terminal
$ bash 12-functions.sh
Sizes
-----
900 B
the second file has 50 MiBExercise
Write a function that repeats a word N times.