Bash – local and global variables

Bash functions can have local variables. This can protect the accidental modification of global variables when function is called inline within same shell. Here are some examples.

Bash function with global variable

The global variable is modified inside function when called within same shell.

#!/bin/bash
function f1 () {
  echo "in f1 x=$x"
  x="HelloNew"
}
x="Hello"
f1
echo "outside f1 x=$x"
in f1 x=Hello
outside f1 x=HelloNew
Env: GNU bash, version 4.3.11

The global variable is not modified inside function when called in sub-shell.

#!/bin/bash
function f1 () {
  echo "in f1 x=$x"
  x="HelloNew"
}
x="Hello"
somevar=$(f1)
echo "outside f1 x=$x"
outside f1 x=Hello
Env: GNU bash, version 4.3.11

Note that in both cases (same shell and sub-shell), global variables can be read and used inside function. Only when executed in same shell, modification is visible outside function.

Bash function with local variable

Example of bash function with local variable.

#!/bin/bash
function f1 () {
  local x="HelloNew"
}
x="Hello"
f1
echo "outside f1 x=$x"
outside f1 x=Hello
Env: GNU bash, version 4.3.11

Bash function with multiple local variable

Example of bash function with multiple local variable.

#!/bin/bash
function f1 () {
  local x="HelloNew",y="HelloNew"
}
x="Hello"
y="Hello2"
f1
echo "outside f1 x=$x"
echo "outside f1 y=$y"
outside f1 x=Hello
outside f1 y=Hello2
Env: GNU bash, version 4.3.11

Bash – protect a variable by making it readonly

In case you have global variables which are initialised only once, you can make them readonly.

#!/bin/bash
function f1 () {
  x="HelloNew"
}
declare -r x="Hello"
f1
echo "outside f1 x=$x"
outside f1 x=Hello
Env: GNU bash, version 4.3.11

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments