LinuxShell Handling Variables on the System Explained
- I. Introduction to Variables in the Shell
- 1.1 Introduction to variables
- 1.2 Environment and Local Variables
- 1.3 Predefined variables
- II. Use of local variables
- 2.1 Introduction to Local Variables
- 2.2 Defining Local Variables
- 2.3 Viewing Local Variables
- 2.4 Canceling Environment Variables
- 2.5 Querying Variable Values
- 2.6 Use of local variables
- III. Environmental variables
- 3.1 Introduction to Environment Variables
- 3.2 Defining Environment Variables
- 3.3 Viewing Environment Variables
- 3.4 Canceling Environment Variables
- 3.5 Querying the set environment variable values
- 3.6 Variable use in shell scripts
- Fourth, the use of echo output variable mode
- 4.1 Direct output variables
- 4.2 Using backslash escapes
- 4.3 Using single and double quotes
- 4.4 Replacement with command
- 4.5 Line feed output
- 4.6 Using Variable Expansion
- 4.7 Using Compound Commands
- V. Different ways of referencing variables
- 5.1 Use of the `$()` method
- 5.2 Use of the `$(())` approach
- 5.3 Use of the `${}` method
- 5.4 Summary of the three approaches
- VI. Extended Usage of the `${}` Approach
- 6.1 Extracting strings
- 6.2 Matching Prefix Deletion
- 6.3 Matching Suffix Deletion
- 6.4 Default Assignment of Variables
I. Introduction to Variables in the Shell
1.1 Introduction to variables
exist
shell
In the script, thevariant
It is a container for storing data. Variables can contain various types of data, such as strings, numbers, or arrays. In shell scripts, data can be stored by assigning values to variables, which can then be used in scripts to refer to that data. Variables can also be processed through operations such as arithmetic, merging or comparing. When using variables, you can refer to the value of a variable by its name.
1.2 environment variableand local variables
1. Local variables
-
local variable
: User-defined variable names and values. Also known as local variables, they are only valid in the current shell and will not be inherited to sub-shells.
2. Environment Variables
-
environment variable
: Global variables are visible globally, are declared without any modifiers, and are valid only in the current shell and subshells.
1.3 Predefined variables
This table summarizes the functions and usage of predefined variables
variant | notation | descriptive |
---|---|---|
Number of command line arguments | $# |
Indicates the number of positional arguments in the command line. |
All positional parameter contents | $* |
Represents the contents of all positional parameters as a whole. |
List all location parameters | $@ |
Indicates that all positional parameters are listed, each as a separate item. |
Return status of the previous command | $? |
Indicates the return status after the execution of the previous command, a return value of 0 means the execution is successful, and a non-zero value means there is an exception. |
Current script or program name | $0 |
Indicates the name of the currently executing script or program. |
Process number of the current process | $$ |
Indicates that the process number of the current process is returned. |
Process number of the last background process | $! |
Returns the process number of the last background process. |
II. Use of local variables
2.1 Introduction to Local Variables
Local Variables
- define: Local variables are variables defined inside a particular shell or function, and their scope is limited to the context in which they are defined.
- scope of action: Local variables are valid only inside the Shell or function in which they are defined.
- life cycle: Local variables expire at the end of the context in which they were defined (e.g., when a function returns or a subshell exits).
-
Declarations and modifications: Local variables can be declared by direct assignment, or by using the
local
Keywords.
2.2 Defining Local Variables
At the shell command line, execute the following command to define local variables.
- Defining Local Variables
testaa_local="this is a local variable"
- 1
2.3 Viewing Local Variables
We can use the set command to filter the query for the local variables we just set. set lists all variables, including local variables and environment variables.
[root@openEuler ~]# set |grep testaa
testaa_local='this is a local variable'
- 1
- 2
2.4 Canceling Environment Variables
The environment variable can be canceled using the unset command
unset testaa_loacl
- 1
2.5 Querying Variable Values
We use the $ symbol to apply the variable and the echo command to view the variable value.
[root@openEuler ~]# echo "$testaa_local"
this is a local variable
- 1
- 2
2.6 Use of local variables
interviews: Local (local) variables can only be accessed in the context in which they are defined.
- We edit a simple script -test_loacl01.sh- that
vim test_loacl01.sh
- 1
#!/bin/bash
myLocalVar="local value"
function myFunction {
local localVar="function-local value"
echo "$localVar"
}
myFunction
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- executable script
[root@openEuler ~]# sh test_loacl01.sh
function-local value
- 1
- 2
III. Environmental variables
3.1 Introduction to Environment Variables
Environment Variables
- define: Environment variables are variables defined at the operating system level that are visible to all running processes and can be inherited between subprocesses.
- scope of action: Environment variables are valid system-wide and can be accessed in any shell script or program.
- life cycle: Environment variables usually remain in effect throughout the runtime cycle of the system unless they are explicitly changed or cleared.
-
Declarations and modifications: Use
export
command declares or modifies environment variables.
3.2 Defining Environment Variables
Execute the following command to define environment variables using export.
export ATEST=aa587
- 1
3.3 Viewing Environment Variables
Viewing environment variables with env only
[root@openEuler ~]# env |grep ATEST
ATEST=aa587
- 1
- 2
3.4 Canceling Environment Variables
Execute the following command to cancel the environment variable.
unset ATEST
- 1
3.5 Querying the set environment variable values
Use the echo command to query the value of the environment variable you just set.
[root@openEuler ~]# echo "$ATEST"
aa587
- 1
- 2
3.6 Variable use in shell scripts
If we want to use environment variables and local variables in a shell script, we can use the following method.
vim
- 1
#!/bin/bash
##########################################################
# File Name:
# Version: V1.0
# Author: jeven
# Email: admin@
# Created Time: 2024-07-25 00:33:57
# Description:
##########################################################
# Define an environment variable
export ENV_VAR="environment variable"
# Define a local variable
LOCAL_VAR="local variable"
# Export environment variables
echo "Environment Variable: $ENV_VAR"
# Define a function and use local variables
function printLocal {
local localVar="function-local variable"
echo "Local Variable in Function: $localVar"
}
# Calling functions
printLocal
# Output local variables (still available in the main script)
echo "Local Variable in Script: $LOCAL_VAR"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- executable script
[root@openEuler ~]# sh
Environment Variable: environment variable
Local Variable in Function: function-local variable
Local Variable in Script: local variable
- 1
- 2
- 3
- 4
In this example, the
ENV_VAR
is an environment variable that can be accessed throughout the script, while theLOCAL_VAR
is a local variable, available only in the top-level context of the script.localVar
then it is in theprintLocal
Local variables defined inside a function are valid only inside that function.
Fourth, the use of echo output variable mode
4.1 Direct output variables
In a Linux shell script or on the command line, use the
echo
command to output the contents of a variable is a common practice. Outputting variables directly, which is the easiest way to do this, is done directly in theecho
Just add the variable name at the end. Note that the variable name needs to be preceded by a dollar sign$
to indicate that this is a variable and not ordinary text. If the variable name contains spaces or special characters, you should use double quotes"
Wrap the variables.
variable="Hello, world!"
echo "$variable"
- 1
- 2
4.2 Using backslash escapes
To include the double quotes themselves or other special characters in the output, use a backslash
\
Performs escaping.
message='"Hello, world!" she said.'
echo "$message"
- 1
- 2
4.3 Using single and double quotes
-
single quote (
'...'
): will not parse the variable and will output it as is. -
double quote (
"..."
): will parse the variable and replace its value.
var="world"
echo 'Hello, $var!' # Output: Hello, $var!
echo "Hello, $var!" # Output: Hello, world!
- 1
- 2
- 3
4.4 Replacement with command
Command substitution allows you to use the result of a command as part of a variable.
date_var=$(date)
echo "Today is $date_var"
- 1
- 2
4.5 Line feed output
echo outputs the value of a variable on a newline.
A=100
B=200
C=300
echo -e "$A\n$B\n$C"
- 1
- 2
- 3
- 4
- 5
4.6 Using Variable Expansion
apart from
echo
In addition, the variable expansion feature of the shell can be utilized.
greeting="Hello, world!"
echo "${greeting}"
- 1
- 2
4.7 Using Compound Commands
Compound command structures can be used, such as
{ ... ; }
to ensure thatecho
and variable assignment are done on the same command line.
[root@openEuler ~]# { greeting="Hello, world!"; echo "$greeting"; }
Hello, world!
- 1
- 2
V. Different ways of referencing variables
5.1 Utilization$()
way (of life)
In a Linux shell script, the$()
, $(())
, and${}
are all used to handle variables and expressions in different ways.
- use: Used for command substitution, where the output of a command is used as the value of a variable.
-
grammatical:
$()
Or use old-fashioned backquotes`
(backticks)。 - typical example:
[root@openEuler ~]# result=$(ls -l)
[root@openEuler ~]# echo "$result"
total 120
-rw-r--r--. 1 root root 95400 Jul 17 22:31 7.1.
-rw-------. 1 root root 1060 Jun 27 15:51
-rwxr-x--x. 1 root root 0 Jul 17 17:02
drwxr-xr-x. 2 root root 4096 Jul 23 22:14 filestash
-rw-r--r--. 1 root root 1781 Jul 17 22:42 info_system.txt
drwxrwxr-x. 3 root root 4096 Aug 3 2020 neofetch-7.1.0
-rw-r--r--. 1 root root 745 Jul 25 00:38
-rw-r--r--. 1 root root 145 Jul 24 23:44 test_loacl01.sh
[root@openEuler ~]#
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- Variables can also be applied using
result=`ls -l`
echo "$result"
- 1
- 2
5.2 Utilization$(())
way (of life)
-
use: is used for arithmetic operations and is a form of arithmetic expression.
-
grammatical:
$(())
。 -
typical example:
AA=10 BB=20 sum=$(($AA + $BB)) echo "$sum"
- 1
- 2
- 3
- 4
5.3 Use${}
way (of life)
- use: Used for variable expansion, parameter expansion, and some special variable operations.
-
grammatical:
${}
。 - typical example:
utilization
${}
way, you can refer to the variable directly.
[root@openEuler ~]# name="John Doe"
[root@openEuler ~]# echo "${name}"
John Doe
- 1
- 2
- 3
Parameter Expansion
:
- use: Various modifications and filters can be applied to variable values.
-
grammatical:
${var:offset:length}
,${var#pattern}
,${var##pattern}
, etc.
5.4 Summary of the three approaches
These features are very useful when writing complex shell scripts, allowing you to choose the appropriate way to handle variables and expressions as needed.
-
$()
Used for command substitution to get the output of a command. -
$(())
Specialized for performing arithmetic operations. -
${}
For general variable expansion and parameter expansion, including some special variable operations.
Six,${}
Mode Extended Usage
6.1 Extracting strings
1. Extracting strings:${var:offset:length}
${var:offset:length}
This extension is used to extract substrings from the variable var. offset specifies where to start extracting (indexed from 0), and length specifies how many characters to extract.
[root@openEuler ~]# var="Hello, world!"
[root@openEuler ~]# echo "${var:7:5}"
world
- 1
- 2
- 3
6.2 Matching Prefix Deletion
- Modify variable 1 - match prefix: ${var#pattern}
${var#pattern}
This extension removes the most prefixed match of pattern from the variable var. It only removes the first match. #/home/ is the pattern, which means that the foremost /usr} is removed, resulting in "/local/bin".
path="/usr/local/bin"
echo "${path#/usr}" # Output /local/bin
- 1
- 2
- Modify variable 2-match prefix: ${var##pattern}
${var##pattern}
This extension is similar to ${var#pattern}, but it removes all prefixes of the variable var that match the pattern. In other words, it removes as many matches as possible.
var="/home/user/documents/home"
echo "${var##*/}" # Output "documents/home"
- 1
- 2
Explanation:
The value of var is"/home/user/documents/home"。
##*/ is a pattern indicating that all parts starting with / are deleted.
The first match removes the opening /home/, leaving the"user/documents/home".
Next continue matching until no more matches can be made.
The result is"documents/home"。
- 1
- 2
- 3
- 4
- 5
- 6
6.3 Matching Suffix Deletion
- Modify variable-match suffix: ${var%pattern}
${var%pattern} removes the last part of var that matches the pattern.
var="/home/user/documents"
echo "${var%/*}" # Output "/home/user"
- 1
- 2
6.4 Default Assignment of Variables
- Set variable value: ${var:=word}
${var:=word}: sets var to word if it is unset or null; otherwise returns the value of var.
[root@openEuler ~]# var=""
[root@openEuler ~]# echo "${var:=Hello, world}"
Hello, world
[root@openEuler ~]# echo "$var"
Hello, world
- 1
- 2
- 3
- 4
- 5
- ${var:-default}
Returns default if var is empty or unset; otherwise returns the value of var.
[root@openEuler ~]# var=""
[root@openEuler ~]# echo "${var:-hello}"
hello
[root@openEuler ~]# var="aa"
[root@openEuler ~]# echo "${var:-hello}"
aa
- 1
- 2
- 3
- 4
- 5
- 6
- ${var:+word}
Returns word if var is set and not null; otherwise returns the empty string.
[root@openEuler ~]# var="aa"
[root@openEuler ~]# echo "${var:+hello}"
hello
[root@openEuler ~]# var=""
[root@openEuler ~]# echo "${var:+hello}"
[root@openEuler ~]#
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- ${var:?word}
If var is set, prints word and exits the shell script; otherwise it returns -bash: word is not set.
[root@openEuler ~]# name="John"
[root@openEuler ~]# echo "Hello, ${name:?Name is not set.}"
Hello, John
[root@openEuler ~]# echo "Hello, ${age:?Age is not set.}"
-bash: age: Age is not set.
- 1
- 2
- 3
- 4
- 5