Global Variable

noun

say it: “GLOH-bul VAIR-ee-uh-bul” /ˈɡloʊbəl ˈvɛəriəbəl/

A variable that a whole script shares, its functions included, so any of them can read it or change it.

What is a global variable in bash?

A global variable is shared by the whole script, its functions included. In bash, every variable is global unless local says otherwise, so a function that uses the same name writes over the script's value, with no warning.

add_up() {
  total=0
  for m in "$@"; do total=$((total + m)); done
}
total=45
add_up 4 6 3
echo "The drive: $total minutes"   # The drive: 13 minutes

In a sentence

  • “In bash, total was a global variable, so the function that added up songs wrote over the drive's length.”
  • “Sam keeps the folder name in a global variable at the top of the script so every function can use it.”

Level: Journeyman · More Unix terms at this level

Updated

In other subjects