"Shell" Programming Specifications and Variables

1. Shell script

1. The concept of Shell script

What is a shell? It is the interface, application program, etc. that communicate with the kernel. For example, if you want to play music, your computer shelltells the kernel of the operating system that the user wants to open the music through the command shell you enter to open the music. The kernel is scheduling and memory management through cpu. Disk input and output, etc. work. Move the hardware. At this time, the sound card will work, and the hardware is the actual work 硬件and the actual worker.

  • Save the commands to be executed in sequence to a text file
  • Give the file executable permission
  • Various Shell control statements can be combined to complete more complex operations
2. Application Scenarios of Shell Script
  • repetitive operation
  • interactive task
  • batch transaction processing
  • Service running status monitoring
  • Timing task execution
3. The role of Shell
Command interpreter, "translator between the system kernel and the user, responsible for interpreting the command line

insert image description here

  • Automated operation and maintenance
  • Batch repetitive operations can be scripted and run automatically with scheduled tasks
  • Sincerely light administrator workload
  • Improve the speed of processing text files
  • Avoid configuration errors
    The shell is a string-oriented programming language, can be combined with other languages ​​such as Python. For example, a complex function can be implemented using a Python script, and then this script can be called in the shell to achieve more complex functions. Or conversely, it is also possible to call external Shell scripts in Python scripts to improve the efficiency of automation.
5. Composition of Shell script

1. Script declaration (interpreter):

If the first line is "#!/bin/bash", it means that the code statement below this line is interpreted and executed by the /bin/bash program, #! /bin/bans is the default interpreter. There are other types of interpreters, such as #! /usr/bin/python, #!/usr/bin/expect.

2. Comment information: Statements starting with "#" are indicated as comment information, and the commented statements will not be executed when running the script.
3. Executable statement: such as the echo command, used to output the characters between ""

vim /root/first.sh
#!/bin/bash
# This is my first shell-script.
cd /boot
echo "当前的目录位于:"
pwd
echo"其中以 vml 开头的文件包括:"
ls -lh vml*
Guidelines for writing shell scripts
(1)脚本声明                 ///bin/bash
(2)注释信息               //行首以#号开头定义注释信息,被注释的行内容将不会被执行
(3)可执行语句              //编写要执行的脚本代码

2. Shell programming specification

1. Execution of Shell script

(1) Use absolute/relative paths to specify the script file to run, the user needs to have the execution right x, and the script will run in the subshell environment (2)
Execute the script file to run with the bash/sh program, no execution permission is required, and the script will run in Run in the subshell environment
(3) Use source/ to specify the script file to run, and the script will run in the current shell environment (it will affect the current directory, variable values ​​and other factors)

Method 1: The command to specify the path requires the file to have x permission
chmod +x /root/irst.sh
指定绝对路径: /root/first.sh
指定相对路径: ./first.sh
Method 2: Specify the shell to interpret the script, and do not require the file to have x permissions
sh 脚本路径: sh first.sh
source 脚本路径: . first.sh 或者 source first.sh
2. Redirection and pipeline operations
2.1 Interactive hardware device
  • Standard Input: Receive user-entered data from this device
  • Standard output: output data to the user through this device
  • Standard Error: Report execution errors via this facility
type 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
2.2 Redirection operation
type operator use
Redirect input < Read data from the specified file instead of typing from the keyboard
redirect output > Output 保存到the file specified by the result (overwrite the original content)
>> 追加到The end of the file specified by the output result
standard error output 2> The file specified by the error message 保存到(overwriting the original content)
2>> 追加到In the file specified by the error message
mixed output &> Put the contents of standard output and standard error 保存到in the same file
>File2>&1 Print standard error to 重定向到standard output
2.3 Pipeline operation symbol "|"

Output the result of the command on the left as the processing pair of the command on the right

cmd | cmd2 [... | cmdn]

3. Shell script variables

1. The role and type of Shell variables

1.1 The role of variables

  • Used to store specific parameters (values) that the system and users need to use

    • Variable name: Use a fixed name, which is preset by the system or defined by the user
    • Variable value: can change according to user settings and system environment changes

1.2 Types of variables

  • Custom variables: defined, modified and used by users themselves

  • Special variables: environment variables, read-only variables, location variables, predefined variables

2. Custom variables
2.1 Define a new variable
  • Variable names start with a letter or underscore, are case-sensitive, and are recommended to be all uppercase
变量名=变量值

insert image description here

2.2 View the value of the variable
echo     $变量名

[root@localhost ~]# Product=Python
[root@localhost ~]# Version=2.7.13
[root@localhost ~]# echo $Product
Python
[root@localhost ~]# echo $Product $Version
Python 2.7.13

insert image description here

2.3 Use numbers when assigning values
  • Double quotes: allow to use other variable values ​​​​through symbols (will use other variable values ​​​​with symbols (will putSymbols use other variable values ​​(will be treated as special symbols to refer to the value of variables)
  • Single quotes: It is forbidden to quote other variable values, as ordinary characters (will be treated as ordinary characters (will be treated asTreated as ordinary characters (will treat etc. as special).
    Backtick: command substitution, extract the output of the command after execution

insert image description here

2.4. Assigning values ​​to variables from keyboard input
read [p“提示信息”] 变量名

insert image description here
insert image description here

2.5 Setting the scope of variables
格式1:export  变量名 ...
格式2:export  变量名=变量值 ...
//两个格式可以混合使用

insert image description here
set to global

export   变量名-【=值】     //设置变量为全局变量,在所有shell环境有效

insert image description here

2.6. Operations on integer variables
Method 1: expr $

insert image description here

Method 2: echo $(())

insert image description here

Method 3: echo $【】

insert image description here

Method 4: let i variable; echo $i

insert image description here

let   i++
let    ++i

insert image description here
common operators

Addition +
Subtraction -
Multiplication *
division operation ./
Modulo (remainder) operation %
3. Special Shell variables
3.1 Environment variables

Created in advance by the system to set up the user's working environment

  • Configuration files: /etc/profile, ~/.bash_profile
3.2 Common environment variables
  • PWD (current directory), PATH (system command search path)
  • USER (currently logged in user), SHELL (shell environment of currently logged in user), HOME (home directory of currently logged in user), LANG (current system language and character set encoding), HISTSIZE (number of historical commands)
  • env View the environment variables of the current system
method 1:

insert image description here

Method 2:

insert image description here

Modify /etc/profile

insert image description here

3.3. Read-only variables

It is used when the variable value is not allowed to be modified (set a read-only variable, and cannot modify the value or delete it)
insert image description here

3.4. Position variables

insert image description here

$1 ~$9 The first to ninth position variables represent the parameters separated by spaces after the script

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/Wanghwei17/article/details/130378421