Local Variable
noun
say it: “LOH-kul VAIR-ee-uh-bul” /ˈloʊkəl ˈvɛəriəbəl/
A variable that belongs to one function in a script: it exists only while the function runs, and changing it leaves the script's own variables alone.
What is a local variable in bash?
A local variable belongs to one function: local makes it when the function starts, and it disappears when the function ends. The script's own variable with the same name is left alone. Make every variable inside a function local, the loop's variable too.
add_up() {
local total=0 m
for m in "$@"; do total=$((total + m)); done
echo "This half: $total minutes"
}
total=45
add_up 4 3 5 # This half: 12 minutes
echo "The drive: $total minutes" # The drive: 45 minutes
In a sentence
- “Every name a function works with should be a local variable, the loop's counter too.”
- “Sam made total a local variable, and the drive's 45 minutes stopped turning into 13.”
Level: Journeyman · More Unix terms at this level
Updated