function
Create a shell function named NAME.[1]
WARNING:
The declaration of a function must always stand before its use!
Documentation
- bash -c 'help function'
- man 1 'bash' [EN]
Syntax
function NAME {
...
}
NAME() {
...
}
Examples
- Define and use a Bash function
nf::carp() {
# Shows the exact position of an error, prints the error message and
# optionally exits the script.
# The name of this function was derived from the Perl module "Carp".
#
# Arguments:
# $1: Parameter '-e' with error number (optional)
# $@: Error message
#
# Returns:
# 0: Success
# >0: Error
#
# Example:
# nf::carp -e2 'Error running AppleScript!'
# Print the runtime position of the script
if ! nf::runtime_position 1; then
return 1
fi
# If the first argument starts with '-e' followed by a number
if [[ "$1" =~ ^-e([0-9]*)$ ]]; then
# Prints the error message
echo ": ${*:2}"
# Exits the script
exit "${BASH_REMATCH[1]:-1}"
else
# Prints the error message
echo ": $*"
fi
return 0
} 1>&2
foo() {
if [[ -z "${var}" ]]; then
nf::carp 'Argument not available!'
return 1
fi
}
bar() {
foo
}
# Test usage in functions
bar
foo
# Test usage directly in the script
if [[ ! -f "${file}" ]]; then
nf::carp -e2 'Error finding file!'
fi
Output:
test.sh[49]>bar[45]>foo[39]: Argument not available!
test.sh[50]>foo[39]: Argument not available!
test.sh[54]: Error finding file!
References
- ↑ bash -c 'help function'