Reading — step 1 of 5
Learn
~1 min readParameter Expansion and Patterns
Bash functions are simpler than they look — and trickier than they look.
greet() {
local name="$1" # ALWAYS use 'local' for parameters
echo "Hello, $name"
}
greet "Ada"
Bash functions don't really return values — they return an exit status (0-255). To return data, write to stdout:
add() {
echo $(( $1 + $2 )) # output the result
}
result=$(add 3 4) # capture stdout
echo "$result" # 7
$1, $2, ... are positional arguments. $# is the count. $@ is all arguments (use quoted: "$@").
local is critical** — without it, every variable is global. Forgetting local is the #1 source of bash bugs:
count() {
local i
for ((i = 1; i <= 5; i++)); do
echo $i
done
}
Returning structured data — bash can't return arrays. Workarounds:
- Print one element per line, capture with
mapfile:list_users() { echo "alice"; echo "bob"; echo "carol" } mapfile -t users < <(list_users) - Set a global variable
- Use a nameref (Bash 4.3+):
populate() { local -n out=$1 out=(a b c) } populate myarr
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…