How do you return multiple values from a function?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
Options, from simplest:
# 1. Print lines and read them
get_disk() { df -P / | awk 'NR==2 {print $2, $3, $5}'; }
read -r total used pct < <(get_disk)
# 2. Write into caller-named variables with namerefs (Bash 4.3+)
get_mem() { local -n _total=$1 _avail=$2
_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
_avail=$(awk '/MemAvailable/ {print $2}' /proc/meminfo); }
get_mem mt ma
# 3. Set well-known globals (document them)
Avoid eval for this.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat 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.Beginner