Table of Contents

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:

Scope

Feedback

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

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

Documentation / Reference

help function