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:
|
|
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:
|
|
Show Environment Variables with env
We can also use the env command to output the current environment variable:
|
|
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:
|
|
Show Value of a Variable with echo
We can use the echo command to output variable’s value to the screen:
|
|
Variable Operations
Create a Variable for the Current Shell
We can create a variable directly by the name=value format:
|
|
We can try to access this variable in the offspring 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:
|
|
Create an Array Variable
We can create an array variable that contains multiple elements:
|
|
Remove a Variable
We can delete a variable or an array variable through the unset command:
|
|
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