Bash - Function

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

A shell function is an object that:

By convention, the function name starts with an underscore.

Advertising

3 - 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.

4 - Feedback

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

  • have an exit status
  • and produce output streams.

4.1 - 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

Advertising

4.2 - Capturing Value

4.2.1 - Subshell

The function is executed in a SubShell

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

4.2.2 - Global Variable

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

4.2.3 - Local Variable

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

bar() {
   var=$(($1+$2))
}
 
foo() {
   local var
   bar 6 2
   echo "$var"
}
 
foo
8

4.2.4 - 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'
Advertising

5 - 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.

6 - Documentation / Reference