Bash Functions: Difference between revisions
Jump to navigation
Jump to search
Line 37: | Line 37: | ||
echo "we send this to stderr" 1>&2 | echo "we send this to stderr" 1>&2 | ||
} | } | ||
function caller() { | function caller() { | ||
local content | local content | ||
content=$(callee) | content=$(callee) | ||
echo "${content}" | echo "${content}" | ||
} | } | ||
=Executing a Function in Background= | =Executing a Function in Background= |
Revision as of 23:54, 15 July 2017
Internal
Defintion
Syntax
[function] function-name() { ... }
The "function" keyword is optional.
Arguments
The function does not declare its arguments in the signature. They are available in the function's body as $1, $2, etc.
Exit Status
A bash function does not return a value, it only allows to set an exit status, which is a numerical value. 0 indicates success and a non-zero value indicates failure. The exit status is declared with the "return" keyword:
function f() { ... return 0 }
The function's caller can retrieve the exist status with $?.
Returning Values
As mentioned above, functions do not return values. However, we may send content to stdout or stderr from the body of the function, and that content can be captured by the caller as follows:
function callee() { echo "we send this to stdout" echo "we send this to stderr" 1>&2 } function caller() { local content content=$(callee) echo "${content}" }