Local Variables in Functions

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 92 of 205

A local variable is a variable that exists only while a function runs. It is created with the local command inside the function body, and it disappears when the function returns. Local variables let a function use names such as i, name or result for its own work without changing variables of the same name elsewhere in the script.

The need for local comes from a Bash rule that surprises people coming from other languages: variables in a function are global by default. Any variable a function assigns, without local, belongs to the whole script.

Variables Are Global Unless Declared Local

set_name() {
    name="inside"
}

name="outside"
set_name
echo "name is now: $name"

Output:

name is now: inside

The function did not create its own name. It assigned to the script's name and overwrote outside. In a short script this may be harmless, but in a larger one a helper function can silently change a variable that some other part of the script depends on.

A variable that a function creates without local also stays after the function ends. Every new variable inside a function adds to the global namespace of the script.

Declaring a Local Variable

Put local in front of the assignment:

set_name2() {
    local name="inside"
    echo "in function: $name"
}

name="outside"
set_name2
echo "after call: $name"
in function: inside
after call: outside

While set_name2 runs, there are two variables called name: the global one, holding outside, and the local one, holding inside. Inside the function, the name refers to the local variable, which shadows (hides) the global one. When the function returns, the local variable is removed and the name refers to the global variable again, which was never changed.

A local variable that has no global partner simply disappears when the function ends:

make_temp() { local tmpval=42; }
make_temp
echo "tmpval=[${tmpval-unset}]"
tmpval=[unset]

The expansion ${tmpval-unset} (lesson 45) prints the word unset when the variable does not exist, which shows that tmpval is gone.

Syntax

local NAME
local NAME=VALUE
local NAME1=VALUE1 NAME2=VALUE2 NAME3
local [OPTIONS] NAME=VALUE
  • One local command can declare several variables, separated by spaces.
  • A name without =VALUE is declared local but not set.
  • The options are the same as those of declare: -i (integer), -a (indexed array), -A (associative array), -r (read-only), -x (exported) and -n (name reference, lesson 91).
  • local works only inside a function. At the top level of a script, it is an error:
t92.sh: line 79: local: can only be used in a function

The command returned status 1 and the script continued with the next line.

local Without a Value

In Bash, local x creates a new local variable that is unset, even when a global x exists:

x="global x"
f4() {
    local x
    echo "local x without value: [${x-unset}]"
    x=changed
    echo "inside: $x"
}

f4
echo "after: $x"
local x without value: [unset]
inside: changed
after: global x

Declaring a variable local first and assigning it later is common, for example to keep the exit status of a command substitution (lesson 90):

fail() { echo data; return 3; }

f11() {
    local r=$(fail);  echo "same line: $?"
    local s
    s=$(fail);        echo "split: $?"
}
f11
same line: 0
split: 3

On the same line, $? is the status of local, which succeeded. With the declaration on its own line, the assignment s=$(fail) reports the status of fail.

To start a local variable with a copy of the global value, assign it explicitly. The right-hand side is expanded before the local variable is created, so it still sees the global value:

z=99
f() {
    local z=$z
    echo "local z=\$z gives: $z"
    z=1
}

f
echo "global z: $z"
local z=$z gives: 99
global z: 99

The function works on its own copy and the global z keeps 99.

Loop Variables Need local Too

A for loop assigns its loop variable like any other assignment, so a loop inside a function changes a global variable unless the loop variable is declared local:

count_to()  { for i in 1 2 3; do :; done; }
count_to2() { local i; for i in 1 2 3; do :; done; }

i="mine"; count_to;  echo "i after count_to: $i"
i="mine"; count_to2; echo "i after count_to2: $i"
i after count_to: 3
i after count_to2: mine

count_to left the global i at 3, the last value of the loop (lesson 78). count_to2 declared i local first, so the loop used the local copy. This is easy to miss, because the loop variable is never written with an = sign. The same applies to variables set by read, by (( n++ )) and by printf -v.

Options: Integers, Arrays and Read-Only Locals

local accepts the same attributes as declare:

f6() {
    local a=1 b=2 c
    local -i n="5 + 5"
    local -a arr=(x y z)
    local -r fixed=10
    echo "a=$a b=$b c=[${c-unset}] n=$n arr=${arr[*]} fixed=$fixed"
    fixed=11
    echo "status after assigning to fixed: $?"
}
f6
a=1 b=2 c=[unset] n=10 arr=x y z fixed=10
t92.sh: line 31: fixed: readonly variable
  • local -i n="5 + 5" evaluates the value as arithmetic, so n holds 10.
  • local -a arr=(x y z) creates a local indexed array.
  • local -r fixed=10 creates a read-only local. The later assignment fixed=11 failed with readonly variable. In this Bash 5.2.21 test, the rest of the function body was abandoned after that error (the last echo did not run), which matches what lesson 40 showed for read-only variables in functions. The read-only local is still removed when the function returns, so it does not block the name for the rest of the script.

declare and its older synonym typeset also create local variables when used inside a function. To create or change a global variable from inside a function with declare, add -g:

f7()  { declare d="declared"; typeset t="typeset"; }
f7g() { declare -g g="global via -g"; }

f7;  echo "d=[${d-unset}] t=[${t-unset}]"
f7g; echo "g=$g"
d=[unset] t=[unset]
g=global via -g

Exporting a Local Variable to Child Processes

local -x creates a local variable that is also exported, so programs started by the function see it. When the function ends, the variable disappears along with its export:

f9() {
    local -x MODE=debug
    bash -c 'echo "child sees MODE=$MODE"'
}

f9
echo "after: MODE=[${MODE-unset}]"
bash -c 'echo "new child: MODE=[${MODE-unset}]"'
child sees MODE=debug
after: MODE=[unset]
new child: MODE=[unset]

This sets an environment variable for the commands of one function only, without affecting the rest of the script (environment variables were covered in lessons 36 to 38).

Local Variables and Recursion

Each call of a function gets its own set of local variables. This is what makes recursive functions, functions that call themselves, possible:

countdown() {
    local n=$1
    (( n == 0 )) && return
    countdown $((n - 1))
    echo "back in level n=$n"
}

countdown 3
back in level n=1
back in level n=2
back in level n=3

The call countdown 3 creates a local n holding 3 and calls countdown 2, which creates another local n holding 2, and so on down to 0. As each inner call returns, the local n of the level above becomes visible again with its own value, so the messages print 1, 2, 3. Without local, all levels would share one global n, and every message would show the value left by the deepest call.

A recursive function that computes a value combines local with the print-and-capture method of lesson 91:

fact() {
    local n=$1
    if (( n <= 1 )); then echo 1; return; fi
    local sub
    sub=$(fact $((n - 1)))
    echo $(( n * sub ))
}

echo "5! = $(fact 5)"
5! = 120

unset on a Local Variable

unset removes the local variable. The global variable of the same name is not affected:

y="global y"
f10() {
    local y="local y"
    unset y
    echo "after unset inside: [${y-unset}]"
}

f10
echo "outside: $y"
after unset inside: [unset]
outside: global y

When a Variable Should Stay Global

Not every variable in a function should be local. A function whose job is to update shared state, such as a counter or a setting read from the command line, must assign the global variable:

counter=0
next_id() { counter=$((counter + 1)); }

next_id; next_id; next_id
echo "counter=$counter"
counter=3

A clear way to work is to declare every variable that is only for the function's own use as local, and to leave global only the variables the function is meant to change. Giving those globals distinctive names (for example in capital letters, such as QUIET or TOTAL_ERRORS) makes it obvious at a glance which assignments reach outside the function. Lesson 94 uses this style for a complete script.

How Far a Local Variable Reaches

A local variable is not visible only in the function that declares it. Functions called by that function also see it, and can change it. This is called dynamic scoping, and it is the subject of lesson 93. For now, remember that local protects the caller's variables from the function, and that the function's locals are removed when it returns.

Portability

local is not part of the POSIX standard, but Dash and most other sh implementations support it. One difference matters. In Dash, local x without a value keeps the value of the outer variable, while Bash makes it unset:

x="global x"
g() { local x; echo "local x without value: [${x-unset}]"; x=changed; }
g; echo "after: $x"

Bash printed [unset]; Dash printed [global x]. Both restored the global value afterward. To get the same result in both shells, always give a local variable an explicit value, such as local x= or local x=$x. The local options -i, -a, -A, -r, -x and -n are Bash features (Dash rejected local -n in lesson 91).

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 Local Variables in Functions and get answers drawn from it.

Signed-in readers only.