Scope of variables in shell scripts

Defining functions in the shell can make the code modular and facilitate code reuse. However, the scope of the variables of the script itself and the variables of the function may be confusing for you, so I will sort out the problem here.

(1) The variables defined in the Shell script are global, and their scope starts from the place where they are defined and ends at the place where the shell ends or is displayed and deleted.

Example 1: Scope of script variables

#!/bin/bash
#define the function ltx_func
ltx_func()
{
   echo $v1
   #modify the variable v1
   v1=200 
}
#define the variable v1
v1=100
#call the function ltx_func
ltx_func
echo $v1

Result:
100
200
Analysis: The scope of the script variable v1 starts from where it is defined and ends at the end of the shell. The place where the function ltx_func is called is within the scope of the variable v1, so the variable v1 can be accessed and modified.

(2) The variable defined by the Shell function is global by default, and its scope starts from "the place where the variable is defined when the function is called" to the end of the shell or the place where it is displayed and deleted. Variables defined by a function can be explicitly defined as local, and their scope is limited to the function. But please note that the parameters of the function are local.

Example 2: Global variable defined by function

#!/bin/bash
#define the function ltx_func
ltx_func()
{
  #define the variable v2
  v2=200 
}
#call the function ltx_func
ltx_func
echo $v2

Result:
200
analysis: the function variable v2 is global by default, and its scope is from "the place where the variable definition is executed when the function is called"

Guess you like

Origin blog.csdn.net/luolan_hust/article/details/113726489