Bash functions: Difference between revisions

From wikinotes
Line 60: Line 60:
fi
fi
</source>
</source>
</blockquote><!-- functions with returnval -->


== nested functions ==
== nested functions ==
Line 74: Line 75:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- nested functions -->
</blockquote><!-- nested functions -->
</blockquote><!-- functions with returnval -->
</blockquote><!-- functions -->
</blockquote><!-- functions -->

Revision as of 15:03, 16 July 2021

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 (...)

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