Bash has two types of scopes: Global scopes, namely the declared variables by default, and local scopes.
1) global variable declaration involves the following situations:
#!/bin/bashmm=12 #visible globallyfunc() { mn=34 #visible globally echo "mc=${mc}" #is visible}mc=35 #visible globally# echo "mn={$mn}" #is not visiblefuncecho "mm=${mm};mn=${mn};mc=${mc}"
However, the global variable Mn declared in the function is invisible before the main function is called.
2) local scope: When declaring a variable, add the local keyword before and apply it only to the function. Its scope
Only visible in the current function block and Its subfunctions.
#!/bin/bashfunc1() { local loc1=11 echo "func1 loc1=${loc1}" #is visible}func2() { echo "func2 loc1=${loc1}" #is visible}func1echo "local loc1:${loc1}" #not visible
There is a special case: when the Declaration of local variables and the setting is in a single command line, the operation order is displayed, the variable is set first,
Then, limit the scope of the variable. This result is reflected in the return value.
As follows:
#!/bin/basht=$(exit 1)echo $? # return 1echo "t=${t}"func() { t1=$(exit 1) echo $? # return 1 echo "t1=${t1}" local t2=$(exit 1) echo $? # return 0 echo "t2=${t2}" local t3 t3=$(exit 1) echo $? # return 1 echo "t3=${t3}"}func()