Function context and introspection
Bash provides call-stack information for diagnostics. In a function, ${FUNCNAME[0]} names the current function and ${FUNCNAME[1]} normally names its caller when present. ${BASH_SOURCE[0]} identifies the file defining the current function; ${BASH_SOURCE[1]} is its caller’s source file when available. ${BASH_LINENO[0]} gives the line where the current function was invoked in that caller file, while LINENO gives the current execution line. caller 0 reports the current function’s calling context; its exact output depends on script path and line positions. In a file executed directly, ${BASH_SOURCE[0]} and $0 usually match; when sourced they normally differ. This is a useful conventional guard for a trusted Bash file, not a universal proof of execution mode: invocation names, symlinks, stdin and unusual environments matter. Check array elements for availability outside functions. Never log confidential arguments or environment variables merely to debug a call stack. The fixture-writing commands are checked before running or sourcing the generated files. The line number inside trace.bash is unchanged because the guard is outside the here-document content.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Inspect function names
inner() { printf '%s -> %s\n' "${FUNCNAME[1]}" "${FUNCNAME[0]}"; }outer() { inner; }outerExpected stdout:
outer -> innerIndex zero identifies inner, index one outer.
Inspect source and call line
cat > trace.bash <<'SCRIPT' &&show() { printf '%s:%s\n' "${BASH_SOURCE[0]##*/}" "${BASH_LINENO[0]}" caller 0}showSCRIPTbash trace.bashExpected stdout:
trace.bash:55 main trace.bashThe call is on line 5 in this exact generated fixture.
Guard direct execution
cat > module.bash <<'SCRIPT' &&report() { printf '%s\n' helper; }if [[ ${BASH_SOURCE[0]} == "$0" ]]; then printf '%s\n' directfiSCRIPTbash module.bash &&source ./module.bash &&reportExpected stdout:
directhelperThe tested direct invocation prints direct; sourcing only defines the helper.
Common mistakes
Do not confuse the line of a call with the line currently executing. Do not hardcode stack paths or assume every frame exists; use defaults and guard optional information.
Practice
Create two nested functions and log the current and calling function names. Move the call to another line and observe BASH_LINENO. Create a trusted file that prints a message only when executed directly, then source it and call its helper.
Next: Redirections and file descriptors