Bash Functions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

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.


For more than 9 arguments, always refer to arguments using ${}: ${10} not $10. If you use $10, you'll actually get the first argument ($1) with a "0" appended to it.

The argument count is obtained with $#.

The shift keyword "shifts" to the left the argument list, discarding $1 and assigning to $1 the value that was previously assigned to $2, to $2 the value that was previously assigned to $3, and so on. shift's exit code is 0 if there were still arguments to shift, 1 otherwise.

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
 }

If there is no explicit "return" keyword, the function's exit status is the exit status of last executed statement.

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}"
 }

Command substitution demonstrated above will capture the content that is being sent to stdout into the local variable "content". The content sent to stderr will be sent to the stderr of the executing shell.

Recommended Style

# Function documentation 
# Returns to stdout: ...
# Returns to stderr: ...
function some-function() {

    local arg1=$1  # arg1 documentation
    local arg2=$2  # arg1 documentation
    ...
}

Executing a Function in Background