Bash functions: Difference between revisions
From wikinotes
Line 64: | Line 64: | ||
== nested functions == | == nested functions == | ||
<blockquote> | <blockquote> | ||
You can have nested functions in bash by replacing <code>{...}</code> with <code>(...)</code> | You can have nested functions in bash by replacing <code>{...}</code> with <code>(...)</code> (declaring them in a subshell).<br> | ||
Since this is a subshell, you cannot change directory. | |||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> |
Revision as of 15:54, 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 pittmanYou 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" finested 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" )