caller
Display function call information (stack frame)
TLDR
Print the line and filename where the current function was called
Print the line, function and filename where the current function was called
Print the line, the function name and the filename of a function call n frames back
SYNOPSIS
caller [N]
PARAMETERS
N
An optional integer representing the depth in the call stack. If omitted or 0, it refers to the immediate caller. If N is 1, it refers to the caller of the immediate caller, and so on.
DESCRIPTION
The caller command is a Bash built-in that allows inspecting the call stack of shell functions. When executed inside a function, it outputs information about the function that called it. This information typically includes the line number, the source file name, and optionally the name of the calling function. It's an invaluable tool for debugging complex shell scripts, helping developers understand the flow of execution and identify where a particular function was invoked from.
By providing an optional integer argument N, caller can ascend the call stack, revealing information about callers further up the chain, making it powerful for analyzing deeply nested function calls.
CAVEATS
The caller command is a Bash built-in and is not universally available in all shells (e.g., it might not exist or behave differently in zsh or ksh).
It must be executed within a shell function to provide meaningful output; calling it directly from the script's top level or a subshell will typically result in an error or empty output.
The output format (line number, file name, function name) is specific to Bash and might vary if an equivalent command exists in other shells.
OUTPUT FORMAT
The standard output format for caller is line_number filename [function_name]. For example, 10 myscript.sh my_function. If the caller was not a named function (e.g., a sourced script or the top level of the current script), function_name will be omitted.
COMMON USE CASES
Beyond general debugging, caller is frequently used in error handling functions to report where an error originated. It's also useful in logging to add context (file, line, function) to log messages.
HISTORY
The caller built-in was introduced in Bash 2.0. Its primary purpose was to provide better debugging capabilities for shell scripts, allowing scripters to understand the origin of function calls, which was previously difficult to ascertain without manual tracing or complex trap mechanisms.