20 Local, Global and scope of variables - kumar159man/MyShellLearning GitHub Wiki
By default variables are global in a shell script
#!/usr/bin/bash
sample()
{
x=10
echo "Enclosed under function the value of x is :$x"
}
sample
echo "Value of x outside the function is :$x"
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./scope.sh Enclosed under function the value of x is :10 Value of x outside the function is :10
In order to limit the scope of the variable to local then local keyword is used. local keyword can be only be used inside a function
#!/usr/bin/bash
sample()
{
local x=10
echo "Enclosed under function the value of x is :$x"
}
sample
echo "Value of x outside the function is :$x"
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./scope.sh Enclosed under function the value of x is :10 Value of x outside the function is : myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$
- local keyword used outside
#!/usr/bin/bash
sample()
{
local x=10
echo "Enclosed under function the value of x is :$x"
}
sample
local x=11
echo "Value of x outside the function is :$x"
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./scope.sh Enclosed under function the value of x is :10 ./scope.sh: line 10: local: can only be used in a function Value of x outside the function is : myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$
- Use return to access local variable
#!/usr/bin/bash
sample()
{
local x=10
echo $x
}
y=$(sample)
echo $y
Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./scope.sh 10 myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$