Bash - Function

About

A shell function is an object that:

By convention, the function name starts with an underscore.

Syntax

[ function ] name () compound-command [redirection]

where:

  • function is a optional reserved word
  • name is the function name.
  • () If the function reserved word is supplied, the parentheses are optional.
  • compound-command is the body of the function. Usually a list of commands between { and }, but may be any compound command. compound-command is executed whenever name is specified as the name of a simple command.
  • redirection. Any redirections specified when a function is defined are performed when the function is executed.

Feedback

Bash functions don't return anything or store value in variable, they only:

  • have an exit status
  • and produce output streams.

Exit Status

The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists.

When executed, the exit status of a function is the exit status of the last command executed in the body that can be overwritten with the return function

Capturing Value

Subshell

The function is executed in a SubShell

foo() {
   echo "Nico"
}
x=$(foo)
echo "foo returned '$x'"

Global Variable

foo() {
   return="Return Value"
}
foo
echo "foo returned '$return'"

Local Variable

Bash - local - Variable declaration in function - (Builtin)

bar() {
   var=$(($1+$2))
}

foo() {
   local var
   bar 6 2
   echo "$var"
}

foo
8

File redirection

Storing the value in a file.

# The function
foo() {
   echo "Returned Value" > "$1"
}

# The temp file
tmpfile=$(mktemp)

# The function call
foo "$tmpfile"

# Retrieving the value
echo "foo returned '$(<"$tmpfile")'"

# Close (removing the resource)
rm "$tmpfile"
foo returned 'Returned Value'

Features

  • Bash functions don't return anything or store value in variable, they only produce output streams.
  • Passable: Nnothing is “passable”, especially not arrays. Bash uses strictly call-by-value semantics (magic alias hack excepted).
  • Scope: functions are always global (have “file scope”), so no closure.
  • Nesting: Function definitions may be nested, but these are not closures, though they look very much the same.
  • Functions are not passable (first-class),
  • Namespace: Reusable functions can't be guaranteed free of namespace collisions unless you resort to weird naming rules to make conflicts sufficiently unlikely.

Documentation / Reference


Powered by ComboStrap