当前位置:网站首页>Shell script - global variables, local variables, environment variables
Shell script - global variables, local variables, environment variables
2022-07-29 07:52:00 【sg-expert】
Shell The scope of variables can be divided into three types :
Some variables can only be used inside functions , This is called a local variable (local variable);
Some variables can be in the current Shell In process use , This is called a global variable (global variable);
Some variables can also be used in child processes , This is called an environment variable (environment variable).
Shell local variable
Shell Custom functions also support , however Shell Functions and C++、Java、C# One difference between functions in other programming languages is : stay Shell The variables defined in the function are also global variables by default , It has the same effect as defining variables outside a function . Look at the code below :
#!/bin/bash
# Defined function
function func(){
a=100
}
# Call function
func
# Variables inside the output function
echo $a
Output results :
100
a Is defined inside the function , But you can also get its value outside the function , Prove that its scope is global , Not just inside the function .
To limit the scope of a variable to the inside of a function , You can add... To the definition local command , At this point, the variable becomes a local variable . Look at the code below :
#!/bin/bash
# Defined function
function func(){
local a=6
}
# Call function
func
# Variables inside the output function
echo $a
The output is empty , Indicates the variable a Invalid outside function , Is a local variable .
Shell This property of the variable is similar to JavaScript The variables in are similar . stay JavaScript Variables defined within a function , The default is also a global variable , Just add var keyword , It becomes a local variable .
Shell Global variables
The so-called global variable , It means that the variable is in the current whole Shell In the process . Every Shell Each process has its own scope , Don't affect each other . stay Shell Variables defined in , The default is the global variable .
It's important to note that , The scope of the global variable is the current Shell process , Not the current Shell Script files , They are different concepts . Open one Shell The window creates a Shell process , Open multiple Shell The window creates multiple Shell process , Every Shell Processes are all independent , Have different processes ID. In a Shell Can be used in the process source Command execution multiple Shell Script files , At this time, the global variables are valid in these script files .
for example , Now there are two Shell Script files , Namely a.sh and b.sh.a.sh The code for is as follows :
#!/bin/bash
echo $a
b=400
b.sh The code for is as follows :
#!/bin/bash
echo $b
Open one Shell window , Enter the following command :
[net]$ a=99
[net]$ . ./a.sh
99
[net]$ . ./b.sh
400
These three commands are executed in one process , From the output we can see that , stay Shell Variables defined in the form of command line in the window a, stay a.sh Effective in ; stay a.sh Variables defined in b, stay b.sh It also works , Variable b The scope of its role has gone beyond a.sh.
Be careful , Must be running in the current process Shell Script , Cannot run in a new process Shell Script
Shell environment variable
Global variables are only available at the current time Shell Effective in the process , For others Shell Neither process nor child process is valid . If you use export Command to export global variables , Then it works in all child processes , This is called “ environment variable ”.
Where the environment variable was created Shell The process is called the parent process , If a new process is created in the parent process to execute Shell command , So this new process is called Shell Subprocesses . When Shell When a child process is generated , It will inherit the environment variables of the parent process for its own use , Therefore, environment variables can be passed from the parent process to the child process . It's not difficult to understand. , Environment variables can also be passed to the process .
Be careful , Two people who have no father son relationship Shell Processes cannot pass environment variables , And environment variables can only be passed down, not up , namely “ Pass on the son, not the father ”.
Here is a demonstration of the use of environment variables :
[net]$ a=22 # Define a global variable
[net]$ echo $a # At present Shell Medium output a, success
22
[net]$ bash # Get into Shell Subprocesses
[net]$ echo $a # Output in subprocess a, Failure
[net]$ exit # sign out Shell Subprocesses , Return to upper level Shell
exit
[net]$ export a # take a Export as environment variable
[net]$ bash # Re enter Shell Subprocesses
[net]$ echo $a # Output... Again in the child process a, success
22
[net]$ exit # sign out Shell Subprocesses
exit
[net]$ exit # Exit the parent process , End the whole thing Shell conversation
export a This form is defining variables a Then export it as an environment variable , If you want to export as an environment variable while defining , Can write export a=22.
What we have always emphasized is that environment variables are Shell Valid in subprocess , It's not said that it's in all Shell In the process ; If you create a new through the terminal Shell window , Then it's not the present Shell Can be inherited by child processes. , Environment variables for this new Shell The process is still invalid .
Environment variables are also temporary
adopt export The exported environment variables are only applicable to the current Shell Process and all child processes are valid , If the topmost parent process is shut down , Then the environment variables disappear , Other processes cannot be used , So environment variables are also temporary .
Some readers may ask , If I want a variable at all Shell In the process , Whether or not there is a parent-child relationship between them , What to do ?
Only write variables to Shell This can only be achieved in the configuration file !Shell Every time the process starts, it will execute the code in the configuration file and do some initialization , If you put variables in a configuration file , Then this variable will be defined every time the process is started .
边栏推荐
- [FPGA tutorial case 42] image case 2 - realize image binarization processing through Verilog, and conduct auxiliary verification through MATLAB
- Write some DP
- 在一个sql文件中,上面定义一个测试表及数据,下面可以select* from 测试表
- 监听页面滚动位置定位底部按钮(包含页面初始化定位不对鼠标滑动生效的解决方案)
- [summer daily question] Luogu p6320 [coci2006-2007 4] sibice
- [experience] relevant configuration of remote connection to intranet server through springboard machine
- [memo] summary of the reasons why SSH failed? Remember to come next time.
- QT connects two qslite databases and reports an error qsqlquery:: exec: database not open
- Pytest set (7) - parameterization
- Jiamusi Market Supervision Bureau carried out special food safety network training on epidemic and insect prevention
猜你喜欢

Joseph Ring problem

Why don't you like it? It's easy to send email in cicd
![[experience] relevant configuration of remote connection to intranet server through springboard machine](/img/27/25301cce8a4e5fa0c91902c7b734fb.png)
[experience] relevant configuration of remote connection to intranet server through springboard machine

Halcon installation and testing in vs2017, DLL configuration in vs2017

Day 014 二维数组练习
What are the common error types and solutions of black box testing?
![[paper reading | cryoelectron microscope] interpretation of the new subtomogram averaging method in relion 4.0](/img/8d/03e63d651b713f547b090e6e740b06.png)
[paper reading | cryoelectron microscope] interpretation of the new subtomogram averaging method in relion 4.0

MySQL uses date_ FORMAT(date,'%Y-%m')
![[cryoEM] Introduction to FSC, Fourier shell correlation](/img/01/6a4f6041444abfd1d3ca7e0c14b524.png)
[cryoEM] Introduction to FSC, Fourier shell correlation

MySQL 45 | 08 is the transaction isolated or not?
随机推荐
Chaos and future of domestic digital collections
The smallest positive number that a subset of an array cannot accumulate
Android面试题 | 怎么写一个又好又快的日志库?
Dilworth 定理
EF core reading text type is slow_ EF core is slow to read large string fields
Data unit: bit, byte, word, word length
[memo] summary of the reasons why SSH failed? Remember to come next time.
Prepare esp32 environment
"Swiss Army Knife" -nc in network tools
Joseph Ring problem
@Use of jsonserialize annotation
What are the answers about older bloggers?
Zip gzip tar compression Advanced Edition
What are the principles and methods of implementing functional automation testing?
[summer daily question] Luogu p1601 a+b problem (high precision)
How to draw an excellent architecture diagram
关于pip升级损坏导致的问题记录
Day 014 二维数组练习
Amaze UI 图标查询
Solve the problem that CSDN cannot publish blog due to unknown copyright