Bash functions

From wikinotes

variable scope

If you're coming from a different programming language, bash's scope is a bit strange. By default, all variable scope is shared within the entire module.

name="will"

function printname(){
    fullname="$name pittman"
}

echo $fullname
#>will pittman

You can define local arguments (local to the function they are defined in), but you must do so eplicitly.

local fullname="$name pittman"

functions

arguments

function printHello() {
  echo $1  # first arg
  echo $2  # second arg
  echo "hello"
}

See bash arguments .

returncodes

Bash does not return variables. Instead, it returns an exit code (integer). By default, all functions return with an exit code of 0 (success). If you would like to signal that a function did not complete successfully, return 1.

function produce_error() {
    return 1
}

produce_error && echo "success"   # if produce_error succeeds (return 0), echo "success"
produce_error || echo "failed"    # if produce_error fails (return 1), echo "failed"

if produce_error; then
    echo "success"
else
    echo "failed"
fi

nested functions

You can have nested functions in bash by replacing {...} with (...) (declaring them in a subshell).
Since this is a subshell, you cannot change directory.

outer() (        # <-- note '(' (parenthesis)
    inner() {    # <-- note '{' (curly-bracket)
        echo $1
    }
    inner "foo"
)

arrays as return values

#!/usr/bin/env bash

create_array() {
    local -n arr=$1             # use nameref for indirection
    arr=(one "two three" four)
}

main() {
    local my_array
    create_array my_array
    echo "${my_array[1]}"
}

main