Function Scope and Variable Visibility

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 93 of 205

The scope of a variable is the part of a program in which its name can be seen and used. In Bash, scope decides which variable a name refers to when a script has a global variable, a local variable in one function, and perhaps another local variable of the same name in a function further up the chain of calls. Visibility is the related question of which pieces of code, and which other processes, can see a variable at all.

Lesson 92 introduced local. This lesson explains the exact rules Bash uses to look up a name, which differ from the rules of languages such as Python, C or JavaScript, and shows the other boundaries that limit visibility: subshells and child processes.

The Three Places a Variable Can Live

When a script runs, a variable can be:

  1. Global: created at the top level of the script, or inside a function without local. It is visible everywhere in the current shell process.
  2. Local: created with local (or declare without -g) inside a function. It exists only while that function is running.
  3. Exported: a global or local variable marked with export (or local -x). It is also copied into the environment of programs that the shell starts.

The first two describe visibility inside the shell. The third describes visibility outside it.

Bash Uses Dynamic Scoping

Most modern languages use lexical scoping: a function sees the variables of the place where it was written. Bash uses dynamic scoping: a function sees the variables of the place where it was called. When a function uses a name, Bash looks for it in this order:

  1. The local variables of the function that is running.
  2. The local variables of the function that called it.
  3. The local variables of that function's caller, and so on up the chain.
  4. Finally, the global variables.

The first match wins. An example makes the rule visible:

show_color() {
    echo "show_color sees: $color"
}

paint() {
    local color="red"
    show_color
}

color="blue"
paint
show_color

Output:

show_color sees: red
show_color sees: blue

show_color has no variable of its own called color. When it is called from paint, the lookup finds the local color of paint (step 2) before the global one, so it prints red. When it is called from the top level, there is no calling function, and the lookup reaches the global color, so it prints blue. The same function printed different values only because it was called from different places. In a lexically scoped language, show_color would print blue both times.

Called Functions Can Change the Caller's Locals

Dynamic scoping applies to assignments too. A function that assigns a name without local changes the first variable the lookup finds, and that may be a local variable of its caller:

inner() {
    level="changed by inner"
}

outer() {
    local level="outer's own"
    inner
    echo "outer now has: $level"
}

level="global"
outer
echo "global level: $level"
outer now has: changed by inner
global level: global

inner meant to set something called level. The lookup found the local level of outer first, so that is the variable that changed. The global level was untouched, because the local variable of outer was in the way. When outer returned, its local level was removed with the change still inside it.

Following a Chain of Calls

The lookup always uses the current chain of calls, so the same function can see different variables at different moments:

c() { echo "c sees v=$v"; }
b() { local v="from b"; c; }
a() { local v="from a"; b; c; }

v="global"
a
c sees v=from b
c sees v=from a

The chain for the first call of c is a → b → c. The nearest local v is in b. The chain for the second call is a → c, because b has already returned and its local v is gone. The nearest local v is now the one in a.

Bash keeps the current chain in the FUNCNAME array, which can help when you are trying to understand which variables a function can see:

lvl3() { echo "call stack: ${FUNCNAME[*]}"; }
lvl2() { lvl3; }
lvl1() { lvl2; }
lvl1
call stack: lvl3 lvl2 lvl1 main

The first element is the running function and each later element is its caller. main stands for the top level of the script.

When Dynamic Scoping Causes a Clash

Dynamic scoping becomes a problem when a helper function uses a global variable to hand back a result (lesson 91), and a caller happens to have a local variable with the same name:

get_max() {
    result=$1
    for n in "$@"; do (( n > result )) && result=$n; done
}

report() {
    local result="report text"
    get_max 4 9 2
    echo "report's result is now: $result"
}

report
echo "global result: [${result-unset}]"
report's result is now: 9
global result: [unset]

get_max was written to set a global result. Called from report, it overwrote the local result of report instead, and no global result was ever created. Nothing in get_max itself is wrong; the clash only appears because of where it was called from.

There are several ways to avoid this:

  • Print the result and let the caller capture it with $( ) (lesson 91). The function then sets no shared names.
  • Let the caller choose the variable name, with printf -v or local -n (lesson 91).
  • Give the shared variable a name that is unlikely to be used elsewhere, such as GET_MAX_RESULT.
  • Declare the helper's own working variables local. In get_max, the loop variable n should also be local n, for the same reason.

Writing a Global Variable from Inside a Function

declare -g assigns the global variable directly, skipping any local variables found along the chain:

setter() {
    declare -g mode="set with -g"
    echo "inside setter, mode=$mode"
}

user() {
    local mode="user's local"
    setter
    echo "user sees: $mode"
}

mode="original"
user
echo "global mode: $mode"
inside setter, mode=user's local
user sees: user's local
global mode: set with -g

The global mode changed, but inside setter and user the name mode still referred to the local variable of user, because that local variable shadows the global one until user returns. Use declare -g when a function must set a global value no matter where it is called from, and keep in mind that the new value only becomes visible once the shadowing local variables are gone.

Listing the Variables a Function Declared

local with the -p option, used inside a function, prints the local variables of that function:

inspect() {
    local a=1 b=two
    local -p
}
inspect
declare -- a="1"
declare -- b="two"

declare -p NAME prints a single variable with its attributes, which is useful while debugging scope problems.

unset and Dynamic Scoping

unset follows the same lookup. If a function unsets a name that is local in its caller, it removes the caller's local variable, and the name then refers to the next variable in the chain:

g=global
callee() {
    unset g
    echo "callee after unset: [${g-unset}]"
}

caller() {
    local g=local
    callee
    echo "caller after callee: [${g-unset}]"
}

caller
echo "top: [${g-unset}]"
callee after unset: [global]
caller after callee: [global]
top: [global]

In this Bash 5.2.21 run, unset g in callee removed the local g of caller, so both functions saw the global value afterward, and the global g survived. This behavior is rarely what a script needs; it is one more reason to avoid touching names a function did not create.

Functions Themselves Are Always Global

Variables can be local, but function definitions cannot. A function defined inside another function becomes available to the whole script once the outer function has run:

define_helper() {
    helper() { echo "helper runs"; }
}

type helper >/dev/null 2>&1 && echo "helper exists" || echo "helper does not exist yet"
define_helper
helper
helper does not exist yet
helper runs

The inner definition is just a command that runs when define_helper runs. Until then, helper does not exist; afterwards, it exists everywhere, including outside define_helper.

Subshells Are a Hard Boundary

Everything above concerns one shell process. A subshell is a copy of the shell. It starts with copies of all variables, local and global, but any change it makes stays in the copy:

total=0

add_in_sub() { ( total=100 ); }
add_in_sub
echo "after ( ): $total"

printf '1\n2\n3\n' | while read -r n; do total=$((total + n)); done
echo "after pipe: $total"

while read -r n; do total=$((total + n)); done < <(printf '1\n2\n3\n')
echo "after process substitution: $total"

sub_fn() ( total=500; echo "inside: $total" )
sub_fn
echo "after subshell function: $total"
after ( ): 0
after pipe: 0
after process substitution: 6
inside: 500
after subshell function: 6
  • Parentheses ( ) run their commands in a subshell, so total=100 was lost.
  • The loop on the right side of a pipe also runs in a subshell (lesson 61), so the sum was lost.
  • With process substitution, < <( ), the loop runs in the current shell and the sum of 6 is kept.
  • A function whose body is written with parentheses instead of braces, sub_fn() ( ... ), always runs in a subshell. Nothing it assigns can reach the caller, which makes such a function safe to use for code that changes directories or settings temporarily.

Command substitution, $( ), is also a subshell, as lesson 91 showed. Dynamic scoping never crosses this boundary: a subshell can read the variables it inherited, but it cannot change the originals.

Visibility to Other Programs

A program started by the script, such as another Bash script, python3 or env, runs in a separate process. It does not see shell variables at all unless they are exported:

greeting="hello"
bash -c 'echo "child sees greeting=[$greeting]"'
export greeting
bash -c 'echo "after export: [$greeting]"'
child sees greeting=[]
after export: [hello]

Exporting copies the value into the child's environment. The child receives a copy, so a change made in the child never comes back to the script. local -x (lesson 92) limits an exported variable to the commands of one function.

Changing the Behavior of local with Shell Options

Bash has shell options that adjust how local interacts with outer variables. With shopt -s localvar_inherit (Bash 5.0 or later), a new local variable starts with the value of the variable it shadows instead of being unset:

shopt -s localvar_inherit
w="global w"
f() { local w; echo "with localvar_inherit: [$w]"; }
f
shopt -u localvar_inherit
with localvar_inherit: [global w]

Such options change the meaning of every local in the script, so it is usually clearer to write local w=$w where a copy is wanted (lesson 92). shopt is covered in lesson 149.

Reasoning About Scope in a Script

When a variable has an unexpected value inside a function, ask these questions in order:

  1. Did this function declare the name with local? If so, the function's own value is used.
  2. If not, which functions are on the call chain right now (FUNCNAME), and does any of them have a local variable with this name? The nearest one is used and changed.
  3. If none does, the global variable is used and changed.
  4. Is this code running in a subshell (( ), $( ), a pipeline, or a function with a parenthesized body)? If so, changes will not survive.
  5. Is the value needed by another program? Then it must be exported.

Keeping each function's working variables local, and passing values in through arguments (lesson 89) and out through output or status (lessons 90 and 91), means the answer to these questions is almost always the first one.

Portability

Dynamic scoping of local variables also applies in Dash, which shares the same lookup rule for functions that call each other. The differences are in the details: Dash keeps the outer value for local x (lesson 92), and declare, declare -g, local -p, local -n, FUNCNAME, shopt and process substitution are Bash features. POSIX itself does not define local at all, so in strictly portable scripts every function variable is global (lessons 188 and 189).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Function Scope and Variable Visibility and get answers drawn from it.

Signed-in readers only.