Variables in Linux

Types of variables

  1. Environment/Global Variables
  2. 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.

  1. env
  2. set
  3. export
  4. declare

View variables

  1. env is used to print the Environment Variables.
  2. set/declare is used to print the Shell Variables and Environment.
  3. 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

  1. export is used to transform a Shell Variable to a Environment Variable so that child processes can inhert the environment of parent process.
  2. declare -x is used to transform a Shell Variable to a Environment Variable, it is like export command.

The following picture summaries the usages of all commands mentioned above well. https://cdn.jsdelivr.net/gh/gaohongy/cloudImages@master/202311242004665.png

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.

1
2
3
4
5
6
7
8
9
# a.sh
name="file a"
bash b.sh

# b.sh
echo "b out: $(set | grep name)"

# result
% bash a.sh

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# a.sh
name="file a"
export name
bash b.sh

# b.sh
echo "b out: $(set | grep name)"

# result
% bash a.sh
b out: name='file a'

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.

Reference

0%