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.


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"



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

See bash arguments .


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"
    echo "failed"

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"