A shell function is an object that:
By convention, the function name starts with an underscore.
[ function ] name () compound-command [redirection]
where:
Bash functions don't return anything or store value in variable, they only:
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
The function is executed in a SubShell
foo() {
echo "Nico"
}
x=$(foo)
echo "foo returned '$x'"
foo() {
return="Return Value"
}
foo
echo "foo returned '$return'"
Bash - local - Variable declaration in function - (Builtin)
bar() {
var=$(($1+$2))
}
foo() {
local var
bar 6 2
echo "$var"
}
foo
8
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'
help function