Article Directory
- Shell script overview
-
- Application scenarios of Shell script
- The composition of a shell script
- Script execution
- Pipeline operation |
- Interactive hardware device
- Redirect operation
- The role of variables
- Variable type
- Define new variables
- View the value of a variable
- Use quotation marks when assigning values (must remember)
- The read command gets the input
- Variable scope
- Operation of integer variables
- Environment variable
- Location variable
- Predefined variables
- Floating point arithmetic
Shell script overview
Shell is a special application program, it is between the operating system kernel and the user, acting as a "command interpreter" role, responsible for receiving and interpreting the operating instructions (commands) entered by the user, and passing the operations that need to be performed Give the kernel execution and output the execution result.
Bash (/bin/bash) is the default shell used by most Linux versions.
Application scenarios of Shell script
Repetitive operations
Interactive tasks
Batch transaction processing
Service running status monitoring
Timing task execution
...
The composition of a shell script
1. Script declaration (interpreter)
If the first line is "#!/bin/bash", it means that the code statements below this line are interpreted and executed by the /bin/bash program, and #!/bin/bash is the default interpreter. There are other types of interpreters, such as #!/usr/bin/python, #!/usr/bin/expect.
2. Annotation information
Statements beginning with "#" are expressed as comment information, and the commented statements will not be executed when the script is run.
3. Executable statement
For example, the echo command is used to output the string between ""
Script execution
Method 1: The command to specify the path requires the file to have x permission.
chmod +x /root/first.sh
specifies the absolute path: /root/first.sh
specifies the relative path: ./first.sh
Method 2: Specify Shell to interpret the script, and the file is not required to have x permissions.
sh script path: sh first.sh
source script path:. first.sh or source first.sh
Pipeline operation |
The output result of the command on the left side of the pipe symbol "|" is used as the input (processing object) of the right command. Multiple pipes can be used in the same line of command.
Interactive hardware device
Standard input: receive data input by the user from the device.
Standard output: output data to the user through the device.
Standard error: report execution error information through the device
Types of | Device file | File description number | Default device |
---|---|---|---|
Standard input | /dev/stdin | 0 | keyboard |
Standard output | /dev/stdout | 1 | monitor |
Standard error output | /dev/stderr | 2 | monitor |
Redirect operation
Types of | Operator | use |
---|---|---|
Redirect input | < | Read data from the specified file |
Redirect output | > | Save the standard output result to the specified file, and overwrite the original content |
>> | Append the standard output result to the end of the specified file without overwriting the original content | |
Standard error output | 2> | Save the error information to the specified file and overwrite the original content |
2>> | Append the error message to the end of the specified file without overwriting the original content | |
Mixed output | &> | Save standard output and standard error to the same file |
2>&1 | Redirect standard error output to standard output |
ls -lh > log.txt 2>&1 等同于 ls -lh &> log.txt
本来1-->屏幕 (1指向屏幕)
执行>log后, 1-->log.txt (1指向log.txt)
执行2>&1后, 2-->1 (2指向1,而1指向log.txt,因此2也指向了log.txt)
The role of variables
Used to store specific parameters (values) that the system and users need to use
- Variable name: use a fixed name, preset by the system or defined by the user
- Variable value: can be changed according to user settings and changes in system environment
Variable type
Custom variables : defined, modified and used by the user.
Environmental variables : maintained by the system and used to set the working environment.
Location variables : pass parameters to the script program through the command line.
Predefined variables : a type of variable built in Bash that cannot be modified directly
Define new variables
Format: variable name=variable value
Variable naming rules: start with a letter or underscore, case sensitive
View the value of a variable
Format: echo $ variable name
Use quotation marks when assigning values (must remember)
双引号:允许通过$符号引用其他变量值
单引号:禁止引用其他变量值,$视为普通字符
反撇号:命令替换,提取命令执行后的输出结果,`…`和$(…)作用相同
The read command gets the input
method one:
read -p "prompt information" variable name
echo $ variable name
Method Two:
echo -n "prompt information"
read variable name
echo $ variable name
Variable scope
By default, newly defined variables are only valid in the current Shell environment, so they are called local variables. When entering a subroutine or a new sub-Shell environment, local variables can no longer be used.
Global variable
The specified variables can be exported as global variables through the internal command export, so that user-defined variables can continue to be used in all sub-Shell environments.
Format 1 : export variable name
Format 2 : export variable name = variable value
You can use the pstree command to view the Shell environment,
enter the bash command to enter the sub-Shell environment,
press Ctrl+D or enter the exit command to exit the sub-Shell environment
Operation of integer variables
格式:expr 变量1 运算符 变量2 [运算符 变量3]
运算符:+ 加法、- 减法、\* 乘法、/ 除法、% 取余
Commonly used expressions
i=$(expr 12 \* 5)
i=$((12 * 5))
i=$[12 * 5]
let i=12*5
Complementary calculations
i++ 相当于 i=$[$i+1]
i-- 相当于 i=$[$i-1]
i+=2 相当于 i=$[$i+2]
Environment variable
The environment variables are created in advance by the system to set the user's working environment.
Use the env command to view the environment variables in the current working environment.
Variables USER represents the user name, HOME represents the user's home directory, LANG represents the language and character set, and PWD represents the current The working directory where the
variable PATH represents the default search path for executable programs
echo $PATH #查看当前搜索路径
PATH="$PATH:/root" #将/root目录添加到搜索路径
export PATH="$PATH:/root" #输出为全局环境变量
first.sh
Global configuration file for environment variables
For /etc/profile, the variables defined in this file apply to all users. Each user also has its own independent profile (~/.bash_profile). Can be used to change or set an environment variable for a long time.
The readonly command sets read-only variables
Location variable
When executing a command line operation, the first field represents the name of the command or script program, and the remaining string parameters are assigned to the positional variables in order from left to right.
$n:n为数字,$0代表命令本身,$1-$9代表带一个到第九个参数,十以上的参数需要使用大括号表示,比如第十个参数为${
10}
After adding the braces
Predefined variables
$*、$@:表示命令或脚本要处理的参数。
$*:把所有参数看成以空格分隔的一个字符串整体,代表"$1 $2 $3 $4"。
$@:把各个参数加上双引号分隔成n份的参数列表,每个参数是独立的,代表"$1" "$2" "$3" "$4"
The difference, write script
$0: indicates the name of the currently executed script or command.
$#: Indicates the number of parameters to be processed by the command or script.
$?: Represents the return status code after the previous command or script is executed. A return value of 0 indicates that the execution is correct, and any return value other than 0 indicates that the execution is abnormal. It is also often used as the exit value returned by the return exit function in Shell scripts.
Script demo
Floating point arithmetic
Bash does not support floating point operations. If you need to perform floating point operations, you need to use bc, awk to handle
awk operations