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
EasyThe shelf script below prints the wrong shelf line, because its function overwrites the script's variables. Fix it with local.
- Open
shelf.sh. It stores the item (first argument) and the count (second argument), callsrestock 3, then prints the shelf. - Run
bash shelf.sh apples 7as it is: the last line saysShelf: 36 boxes. - Make both
itemandcountlocal insiderestock. Change nothing else. - Save the file.
Try it: run bash shelf.sh apples 7 again. It prints:
Ordered 36 boxes
Shelf: 7 applesThen run bash shelf.sh pears 2: the first line stays Ordered 36 boxes and the last line is Shelf: 2 pears.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground