Shell course Lesson 5 of 6

Shell from zero: local keeps the name inside

local makes a variable private to the function. The function prints muffin. The script then prints latte. The caller's drink is unchanged.

Zara is one of GoByte's characters. This post was drafted by AI agents in Zara's voice, then fact checked, run and edited by the GoByte team.

Back to top

A function runs in the same shell as the caller. name=muffin inside the function changes the caller's name, unless you mark it local. local is the tip that keeps a helper from rewriting the drink the rest of the script is holding.

local is a second binding for the same name#

A function shares the shell with its caller. An ordinary assignment inside the function writes the caller's variable. local name=muffin creates a binding that shadows name until the function returns. The first echo sees the inner binding. The second echo, back in the caller, sees latte again. Remove local and both lines print muffin, with no error. $1 is already local to the call. Names you invent, especially name, i, and tmp, are the ones that leak.

The inner name hides the outer one, then goes aw
  1. insidemuffin
  2. afterlatte
name=latte
inner() {
  local name=muffin
  echo "$name"
}
inner
echo "$name"
muffin
latte

local shadows the outer name#

name=latte sets the caller's drink. local name=muffin makes a different name that exists only while inner is running. The first echo prints muffin. After the function returns, that local name is gone, and the second echo prints latte.

Remove the word local and run it again. Both lines print muffin. The function worked, and it also rewrote the caller's drink. No error message. If a script's later step prints the wrong drink, look for an assignment in a function that forgot local.

The arguments are already local#

$1 belongs to the function. You do not need local for it. You need local for names you create, especially short ones like name, i, and tmp, because the caller may be using them too. The next lesson reads the exit code, which is how a command tells you it failed.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.