Variables in Linux
Types of variables
- Environment/Global Variables
- Shell/Local Variables
The difference between these two variables is that environment variables can be interviewed by child processes, i.e. the so-called global variables are only shared within the process hierarchy of the current process(进程链), existing only between the current process and its child processes. Environment variables of other processes and those of the current process are not shared. But Shell variables can only be interviewed by current process.
Related commands
env
set
export
declare
View variables
env
is used to print the Environment Variables.set
/declare
is used to print the Shell Variables and Environment.echo $<variable name>
is used to print any single variables.
There is a fallible point, set is only used to view the variables, if we want to create a variable, we can use
export <variable-name>=<variable-value>
,declare -x <variable-name>=<variable-value>
or use<variable-name>=<variable-value>
directly.
Edit variables
export
is used to transform a Shell Variable to a Environment Variable so that child processes can inhert the environment of parent process.declare -x
is used to transform a Shell Variable to a Environment Variable, it is likeexport
command.
The following picture summaries the usages of all commands mentioned above well.
Note: The red words represent the command, the dotted lines represent the access to the variables.
Since we have learned about the usages and meanings of all these commands, so let us try to understand the difference between environment variables and shell variables with the picture.
How can we verify the sentence “environment variables can be interviewed by child processes but Shell variables can only be interviewed by current process” ?
Referring to the Comparison of Shell Script Execution Modes, we can use shell script to verify it.
|
|
According to the Comparison of Shell Script Execution Modes, becauce a.sh use the bash
, so a.sh is in the parent process and b.sh is in the child process and the name variable is just a shell variable which is a private data in process where a.sh locates in. So b.sh can’t access this variable.
|
|
Because a.sh use the export
, so the name variable becomes to a environment variable, althought b.sh is in the child progress, it can access this variable.