local – Defines a local variable within a function

The local command is used to define a local variable within a function. A local variable is a variable that is visible only within the function where it is defined. It is not visible to other functions or to the main program.

In Bash, functions are defined using the function keyword or by simply using the function name followed by a set of parentheses. The local command is used to define a local variable within a function.


The syntax for using the local command is as follows:

local [option] name[=value]

Here, name is the name of the variable to be defined, and value is an optional initial value for the variable. If value is not specified, the variable will be initialized to an empty string.

The option argument can be one of the following:

  • -i: The variable is treated as an integer.
  • -r: The variable is read-only.
  • -g: The variable is global.


Here is an example of how to use the local command to define a local variable within a function:


function myfunc {
    local myvar="Hello, World!"
    echo $myvar


In this example, the myfunc function defines a local variable named myvar with the value “Hello, World!”. The echo command then outputs the value of myvar.

When you run this script, it will output “Hello, World!”.


The local command supports the following options:

Option Description
-i Treats the variable as an integer.
-r Makes the variable read-only.
-g Makes the variable global.

Troubleshooting Tips

If you are having trouble with the local command, here are a few tips to help you troubleshoot:

  • Make sure that you are using the correct syntax for the local command.
  • Check that the variable name does not conflict with any other variables in your script.
  • If you are using the -r option, make sure that you are not trying to assign a value to the variable.


  • The local command is only available within functions. It cannot be used outside of a function.
  • If you define a variable with the same name as a global variable, the local variable will take precedence within the function.
  • If you use the local command without any arguments, it will display a list of all local variables within the function.