How do you define a function, pass arguments and return a value?
BeginnerConceptFunctions, exit codes, strict mode and traps
Answer
disk_pct() { # disk_pct MOUNTPOINT -> prints usage percent
local mount=$1
df -P -- "$mount" | awk 'NR == 2 {sub(/%/, "", $5); print $5}'
}
pct=$(disk_pct /var) # "return" data by printing it
if (( pct > 90 )); then ...; fi
Arguments are $1, $2, ... and "$@", just like a script. return N sets the exit status (0 to 255); it is not for data. A function's status without return is the status of its last command.
More on Functions, exit codes, strict mode and traps
What does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.BeginnerWhy can `((count++))` kill a script under `set -e`?Intermediate