Functions
A Bash function groups commands under a name you can call repeatedly — but unlike most languages, it can only hand a numeric exit status back to whoever called it, not an arbitrary value.
Defining and calling a function
bash greet.sh
#!/bin/bash greet() { echo "Hello, $1!" } greet "Sam" greet "Priya"
Terminal output
Hello, Sam! Hello, Priya!
Inside a function, $1, $2, and so on refer to that function's own arguments — not the script's overall command-line arguments, even if the function happens to be called with none.
Local variables
Without local, a variable set inside a function is global by default and can quietly overwrite a variable of the same name elsewhere in the script:
bash local-scope.sh
#!/bin/bash message="outer" show_message() { local message="inner" echo "Inside function: $message" } show_message echo "Outside function: $message"
Terminal output
Inside function: inner Outside function: outer
"Returning" a value
return only sets a numeric exit status (0–255), checked afterward with $? — it can't send back text. To hand back an actual value like a string or number, echo it and capture that output with $(...):
bash double.sh
#!/bin/bash double() { echo $(( $1 * 2 )) } result=$(double 21) echo "Result: $result"
Terminal output
Result: 42
Note:
return 42 does not mean "give back the number 42" the way it would in most languages — it means "exit this function with status code 42," and status codes are conventionally limited to signalling success (0) or one of 255 kinds of failure, not arbitrary data. Use echo + command substitution for real return values, and reserve return for success/failure signaling.