sajad torkamani

By default, variables in Bash are global which means if you define a variable foo in a function A, that variable will be accessible inside other functions too assuming function A has already been executed.

Inside functions, you can define a variable as local so that it’s only be accessible inside that function.

For example, here is a global variable:

#!/usr/bin/env bash

function say_hello() {
  name="Sajad"
  echo "Hello $name"
}

say_hello

if [ -n "$name" ]; then
  echo "name = $name"
else
  echo "name is not defined"
fi

The output of that script is:

name = Sajad

Here’s the same script where we define name as a local variable:

#!/usr/bin/env bash

function say_hello() {
  local name="Sajad"
  echo "Hello $name"
}

say_hello

if [ -n "$name" ]; then
  echo "name = $name"
else
  echo "name is not defined"
fi

Output:

name is not defined

Tagged: Bash