🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Local Variables

A local variable exists only inside the function that creates it. Without the local keyword, a variable set in a function is shared with the whole script.

Variables leak out by default

The function changes score without using local. The new value is still there after the function returns.

score=10
change_score() {
  score=99
}
change_score
echo "Score after the call: $score"

Keep a change inside with local

Here the function uses a local variable with the same name. The inside value is 99, but the outside value stays 10.

score=10
change_score() {
  local score=99
  echo "Inside the function: $score"
}
change_score
echo "Outside the function: $score"

Return a status number

The function ends with return 5. Reading $? right after the call shows that number.

check_files() {
  return 5
}
check_files
echo "The function returned $?"

Example

level=1
update_level() {
  local level=9
  echo "Level inside the function: $level"
  return 4
}
update_level
echo "Return status: $?"
echo "Level outside the function: $level"

Key points

  • By default, a variable set inside a function is global.
  • A global variable can still be read after the function returns.
  • The local keyword keeps a variable inside one function.
  • Outside its function, a local variable is not visible.
  • The return command ends a function and sets a status number.
  • The status from return can be read with $? right after the call.

In this example, the local variable level hides the outer one inside the function. The return command sets the status to four. The outer level still holds one after the call.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the local keyword do to a variable in a function?