29. Bash Shell - Variables Operations
Contents
I believe that people who have learned how to program know what variables are, and at first it can be understood as an alias that points to the data stored in memory.
Although Bash shell and Bourne shell come with many system variables, we could also customize variables ourselves.
Check System Variables
We can view existing system variables in the following ways:
Show System Variables with set
We can pass the output of the set command to the less or more command to see all the variables from the beginning of the output result:
|
|

Pipes set command's result to less command

Use the less command to navigate to the start of the set command's output result.
We can type the q key to exit the the less command’s interactive mode.
Show Environment Variables with printenv
We can use the printenv command to output the current environment variables:
|
|

Prints current environment's variables
Show Environment Variables with env
We can also use the env command to output the current environment variable:
|
|

Prints current environment's variables
The output is quite similar to printenv command’s output result.
Show Shell Variables with export
We can use the export command to output shell variables:
|
|

Prints shell variables
Show Value of a Variable with echo
We can use the echo command to output variable’s value to the screen:
|
|

Prints the variable that contains directories of all the executable files
Variable Operations
Create a Variable for the Current Shell
We can create a variable directly by the name=value format:
|
|

Prints the created MY_NAME variable
We can try to access this variable in the offspring shell:
|
|

Prints the created MY_NAME variable in a child shell
From the screenshot, we can see that we can’t use the MY_NAME variable created by the parent shell in the child shell.
Set a Variable as Shell Variable
The variable we just created can only be accessed in the current shell, what should we do if we want to access it in our offspring shell?
We can set the created variable to the shell variable through the export command in the shell where the variable was created, so that all descendants of the shell can access the variable:
|
|
Reference a Variable in a String
We can reference the created variable in a string:
|
|

Prints a string that referenced the MY_NAME variable
Create an Array Variable
We can create an array variable that contains multiple elements:
|
|

Prints the first and second elements of the created array variable
Remove a Variable
We can delete a variable or an array variable through the unset command:
|
|

Unset the MY_NAME variable, this will also remove the array elements stored in that variable
References 4.3.1 The Set Builtin, 19.3 printenv: Print all or some environment variables, 23.2 env: Run a command in a modified environment
Author Dong Chen
LastMod Sat Mar 2 2019