Menu
CoddyTech

Local Variables

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 13 of 39.

A variable you set inside a function belongs to the whole script. If the script already has a variable with that name, the function overwrites it.

#!/bin/bash
file="report.txt"
backup() {
  file="report.bak"
  echo "Saving $file"
}
backup
echo "Original: $file"

bash save.sh prints Saving report.bak, then Original: report.bak: the function changed the script's file. Write local in front of the assignment to keep the variable inside the function:

backup() {
  local file="report.bak"
  echo "Saving $file"
}

Now the last line prints Original: report.txt. A local variable exists only while its function runs, and the script's variable with the same name keeps its value. local works only inside a function; at the top of a script it prints an error. Make every variable a function uses for its own work local.

challenge icon

Challenge

Easy

The shelf script below prints the wrong shelf line, because its function overwrites the script's variables. Fix it with local.

  1. Open shelf.sh. It stores the item (first argument) and the count (second argument), calls restock 3, then prints the shelf.
  2. Run bash shelf.sh apples 7 as it is: the last line says Shelf: 36 boxes.
  3. Make both item and count local inside restock. Change nothing else.
  4. Save the file.

Try it: run bash shelf.sh apples 7 again. It prints:

Ordered 36 boxes
Shelf: 7 apples

Then run bash shelf.sh pears 2: the first line stays Ordered 36 boxes and the last line is Shelf: 2 pears.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground