Shell Variables
In Shell programming, a variable is a name used to store a data value.
When defining a variable, the variable name does not include a dollar sign ($, as required for variables in PHP), for example:
Note that there must be no spaces between the variable name and the equals sign, which may be different from all the programming languages you are familiar with. At the same time, the naming of variable names must follow the following rules:
- Only contain letters, numbers, and underscores:Variable names can contain letters (case-sensitive), numbers, and underscores_, and cannot contain other special characters.
- Cannot start with a number:Variable names cannot start with a number, but can contain numbers.
- Avoid using Shell keywords:Do not use Shell keywords (such as if, then, else, fi, for, while, etc.) as variable names to avoid confusion.
- Use uppercase letters for constants:By convention, variable names for constants usually use uppercase letters, for examplePI=3.14。
- Avoid using special symbols:Try to avoid using special symbols in variable names, because they may conflict with Shell syntax.
- Avoid using spaces:Variable names should not contain spaces, because spaces are usually used to separate commands and arguments.
Valid Shell variable name examples are as follows:
EXAMPLE="www.example.com" LD_LIBRARY_PATH="/bin/" _var="123" var2="abc"
Invalid variable naming:
# 避免使用if作为变量名 if="some_value" # 避免使用 $ 等特殊符号 variable_with_$=42 ?var=123 user*name=example # 避免空格 variable with space="value"
Avoid spaces on both sides of the equals sign:
# 正确的赋值 variable_name=value # 有可能会导致错误 variable_name = value
In addition to explicit direct assignment, you can also use statements to assign values to variables, such as:
or
for file in $(ls /etc)
The above statement uses a loop to list the file names in the /etc directory.
Using Variables
To use a defined variable, just add a dollar sign before the variable name, like:
Example
echo $your_name
echo ${your_name}
The curly braces around the variable name are optional; you can add them or not. Adding curly braces is to help the interpreter identify the boundary of the variable, such as in the following case:
Example
echo "I am good at ${skill}Script"
done
If you do not add curly braces to the skill variable and write echo "I am good at $skillScript", the interpreter will treat $skillScript as a variable (with an empty value), and the code execution result will not be what we expected.
It is recommended to add curly braces to all variables; this is a good programming habit.
A defined variable can be redefined, such as:
Example
echo $your_name
your_name="alibaba"
echo $your_name
This is legal, but note that when assigning for the second time, you cannot write $your_name="alibaba"; you only add the dollar sign ($) when using the variable.
Read-only Variables
Using the readonly command can define a variable as a read-only variable; the value of a read-only variable cannot be changed.
The following example attempts to change a read-only variable, resulting in an error:
Example
myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.example.com"
Run the script, the result is as follows:
/bin/sh: NAME: This variable is read only.
Deleting Variables
Use the unset command to delete a variable. Syntax:
unset variable_name
A variable cannot be used again after it is deleted. The unset command cannot delete read-only variables.
Example
Example
myUrl="https://www.example.com"
unset myUrl
echo $myUrl
Executing the above example will produce no output.
Variable Types
Shell supports different types of variables, and some of the main types include:
String variables:In Shell, variables are usually treated as strings.
You can use single quotes'or double quotes"to define a string, for example:
my_string='Hello, World!' 或者 my_string="Hello, World!"
Integer variables: In some shells, you can usedeclareortypesetcommand to declare integer variables.
Such variables only contain integer values, for example:
declare -i my_integer=42
Such a declaration tells Shell to treat my_integer as an integer. If you try to assign a non-integer value to it, Shell will try to convert it to an integer.
Array variables:Shell also supports arrays, allowing you to store multiple values in one variable.
Arrays can be integer-indexed arrays or associative arrays. The following is an example of a simple integer-indexed array:
my_array=(1 2 3 4 5)
Or associative arrays:
declare -A associative_array associative_array["name"]="John" associative_array["age"]=30
Environment variables:These are special variables set by the operating system or the user, used to configure the behavior of Shell and affect its execution environment.
For example, the PATH variable contains the path where the operating system searches for executable files:
echo $PATH
Special variables:There are some special variables that have special meanings in Shell, such as$0represents the name of the script,$1, $2, etc. represent the parameters of the script.
$#represents the number of parameters passed to the script,$?represents the exit status of the previous command, etc.
Shell Strings
Strings are the most commonly used and most useful data type in shell programming (apart from numbers and strings, there aren't many other types to use). Strings can use single quotes, double quotes, or no quotes.
Single Quotes
str='this is a string'
Restrictions on single-quoted strings:
- Any character within single quotes will be output literally, and variables in single-quoted strings are not expanded;
- A single quote cannot appear alone in a single-quoted string (even if you escape the single quote), but they can appear in pairs for string concatenation.
Double Quotes
Example
str="Hello, I know you are \"$your_name\"! \n"
echo -e $str
The output is:
Hello, I know you are "example"!
Advantages of double quotes:
- Variables can be used inside double quotes
- Escape characters can appear inside double quotes
Concatenating Strings
Example
# Concatenate using double quotes
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1
# Concatenate using single quotes
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2 $greeting_3
The output is:
hello, example ! hello, example !
hello, example ! hello, ${your_name} !
Getting String Length
Example
echo ${#string} # Outputs 4
When the variable is a string,${#string}is equivalent to${#string[0]}:
Example
echo ${#string[0]} # Outputs 4
Extracting Substrings
The following example starts from the2character of the string and begins extracting4characters:
Example
echo ${string:1:4} # Outputs unoo
Note: the index value of the first character is0。
Finding Substrings
Find the characterioro's position (whichever letter appears first is counted):
Example
echo `expr index "$string" io` # Outputs 4
Note:In the above script,`it is a backtick, not a single quote', don't misread it.
Shell Arrays
bash supports one-dimensional arrays (does not support multi-dimensional arrays) and does not limit the size of the array.
Similar to C language, the subscripts of array elements are numbered starting from 0. To access an element in an array, you need to use a subscript. The subscript can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.
Defining Arrays
In Shell, parentheses are used to represent arrays, and array elements are separated by the "space" symbol. The general form for defining an array is:
数组名=(值1 值2 ... 值n)
For example:
array_name=(value0 value1 value2 value3)
or
array_name=( value0 value1 value2 value3 )
You can also define the individual components of an array separately:
array_name[0]=value0 array_name[1]=value1 array_name[n]=valuen
It is not necessary to use consecutive subscripts, and there is no limit on the range of subscripts.
Reading Arrays
The general format for reading an array element value is:
${array name [subscript]}
For example:
valuen=${array_name[n]}
Use@The symbol can retrieve all elements in the array, for example:
echo ${array_name[@]}
Getting the Length of an Array
The method to get the length of an array is the same as getting the length of a string, for example:
Example
length=${#array_name[@]}
# Or
length=${#array_name[*]}
# Get the length of a single array element
length=${#array_name[n]}
Shell Comments
with#Lines starting with # are comments and will be ignored by the interpreter.
By adding a## sign to each line to set multi-line comments, like this:
Example
# This is a comment
# author: Example
# site:www.example.com
# slogan: What you learn is not just technology, but also dreams!
#--------------------------------------------
##### User configuration area start #####
#
#
# Add script description information here
#
#
##### User configuration area end #####
If during development you encounter a large block of code that needs to be temporarily commented out and later uncommented, what can you do?
Adding a # symbol to each line is too laborious. You can enclose the block of code to be commented in a pair of curly braces and define it as a function. If the function is never called, the code will not execute, achieving the same effect as commenting.
Multi-line Comments
Using Here documents
Multi-line comments can also use the following format:
Comment content...
Comment content...
Comment content...
EOF
Other symbols can also be used instead of EOF:
Example
This is the commented part.
It can contain multiple lines.
COMMENT
:<<'
Comment content...
Comment content...
Comment content...
'
:<<!
Comment content...
Comment content...
Comment content...
!
Directly use the : sign
We can also use the colon:command, and use single quotes'to enclose multiple lines of content. Since the colon is an empty command, these contents will not be executed.
The format is:: + space + single quote。
Example
This is the commented part.
It can contain multiple lines.
'