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

Local Variables

In this page:

  1. Local Variables

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"

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.