Bash variables are defaults to global
What makes a variable local?
- A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope." In a function, a local variable has meaning only within that function block.
Ex:
local variable name
func ()
{
local loc_var=23
# Declared as local variable.
# Uses the 'local' builtin.
echo "\"loc_var\" in function = $loc_var"
global_var=999
# Defaults to global.
echo "\"global_var\" in function = $global_var"
}
func
# Now, to see if local variable "loc_var" exists outside function.
echo "\"loc_var\" outside function = $loc_var"
# $loc_var outside function =
# No, $loc_var not visible globally.
echo "\"global_var\" outside function = $global_var"
# $global_var outside function = 999
# $global_var is visible globally.
exit 0
- Before a function is called, all variables declared within the function are invisible outside the body of the function, not just those explicitly declared as local
func ()
{
global_var=37
# before the function has been called.
} # END OF FUNCTION
echo "global_var = $global_var"
# global_var =
# Function "func" has not yet been called,
# so $global_var is not visible here.
func
echo "global_var = $global_var"
# global_var = 37 Has been set by function call.
- Using the declare builtin restricts the scope of a variable
foo ()
{
FOO="bar"
}
bar ()
{
foo
echo $FOO
}
bar
# Prints bar
However . . .
foo (){
declare FOO="bar"
}
bar ()
{
foo
echo $FOO
}
bar
# Prints nothing.
Very good article...Thanks
ReplyDeleteWell post its tell us how to make math diagrams with new method i really like this thanks for share it sop editing service .
ReplyDeleteLinux Training in Chennai
ReplyDeleteRHCE Training in Chennai
Best Linux Training Center in Chennai
Red Hat Training in Chennai
Best Linux Training Institute in Chennai
Red Hat Linux Trainng in Chennai
cdiweld rest tomcat junit
This comment has been removed by the author.
ReplyDeleteThanks for a wonderful share
ReplyDeleteIt is very important that what you write.
ReplyDeleteCommonly we attain confused when we finally hear the exact terms website development service in addition to internet developer getting used interchangeably. But thoughts is broken done looking over this, all your individual confusions may perhaps disappear. Poof! kissmanga
ReplyDeletehttp://www.bashguru.com/2009/08/gcd-of-more-than-two-numbers.html?showComment=1543883280359#c5987719078380583062
ReplyDelete