Create Local Variable In Shell Script

  • All variables are global by default.
  • Modifying a variable in a function changes it in the whole script. This could lead to issues.
  • local command can only be used within a function.
  • It makes the variable name have a visible scope restricted to that function and its children only.
  • All function variables are local. This is a good programming practice.

example

#!/bin/bash
packageName="nginx"
function install(){
    local myname="gaurav"
    echo "installing ${1}"
}

function configuration(){
    packageName="tomcat"
    echo "config ${1}"
}

echo "first ${packageName}"
echo "myname = ${myname}"
install "${packageName}"
echo "myname = ${myname}"
echo "second ${packageName}"
configuration "${packageName}"
echo "third ${packageName}"

output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./variables-in-functions.sh
first nginx
myname =
installing nginx
myname =
second nginx
config nginx
third tomcat

Demo Video

Click Here for Demo Video