← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 7 of 13

Local Variables

A local variable is like a whiteboard that gets wiped when a meeting ends. Its value only lives inside the function and cannot mess up labels used elsewhere.

In this page:

  1. Local Variables
Syntax
bash
function_name() {
  local variable_name=value
}

Local Variables

By default, variables set inside a function are global and can clash with variables outside it.

The local keyword scopes a variable to just that function call, preventing it from leaking into or overwriting the caller's variables. Using local for anything that isn't meant to be shared is good practice.

Warning: Without local, a variable assigned inside a function silently overwrites any same-named global variable.

Example: Local Variables

bash
#!/bin/bash
message="global value"

show_message() {
    local message="local value"
    echo "Inside function: $message"
}

show_message
echo "Outside function: $message"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting local, so variables leak into the global scope.
  2. Using local x=$(cmd) and losing the exit status of cmd.
  3. Expecting local to work outside a function, which gives an error.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.