Summary of the first two chapters of Shell

Chapter 1--Basic knowledge of Shell

1. Shell classification

  • Bourne Shell: identified as sh, the shell was written by Steve Bourne at Bell Labs, and this shell is the default shell for root users in many Unix systems

  • Bourne-Again Shell: identified as bash, which is the default shell for most localhost distributions

  • Korn Shell: identified as ksh, fully upwardly compatible with Bourne Shell, including many features of C Shell

  • C Shell: identified as csh, its syntax is similar to C language

View the shell operations supported by the current system

 View the default shell of the current system

Two, the basic elements of shell script

  1. Statement: Declare which command interpreter is used to interpret and execute the statements in the current script file, the general interpreter is #!/in/bash
  2. Command: an executable statement to achieve a certain function of the program
  3. Comments: Explain the function of some codes, and improve the readability of the program by adding comments to the code

Classification of annotations:

  • single line comment
#comment1
#comment2
  • Multi-line comment: colon + any two words, the comment content can be inserted between the two words
:<<Block
注释内容
Block

3. Shell script writing specification

  1. The script file name should be well-known, such as backup_mysql.sh
  2. Specify the script interpreter at the beginning of the file #!/bin/sh or #! /bin/bash
  3. Add version privileges and other information at the beginning
#Date:日期
#Author:作者
#Mail:联系方式
#Function:功能
#Version:版本

      4. Try not to use Chinese comments in the script

      5. Use more internal commands

        Commonly used internal commands: echo eval exec export read shift exit

  • echo can output information on the screen
echo parameter option illustrate
-n Do not wrap the output content
-e parse escape characters

                     

escape character illustrate
\n new line
\r carriage return
\t Tabs
\b backspace
\v vertical tab

                       

  •  eval

Command format: eval args

Function: When the shell program executes to the eval statement, the shell reads in the parameters args and combines them into a new command and executes it

  • The exec command can execute the specified command without creating a new child process. When the specified command is executed, the process terminates
  • export sets or displays environment variables
  • The read command can read information such as strings from the standard input, and pass it to the variables defined inside the shell program

-p prompt: set prompt information

-t timeout: Set the input waiting time, the default unit is seconds

  • shift: Every time the shift statement is used in the program, all positional parameters will be shifted one position to the left in turn, and the positional parameter $# will be reduced by one until it reaches 0
  • exit: Exit the shell program. After exit, you can optionally specify a number as the return status

6. Code indentation: standardized coding makes the code more beautiful

4. How to execute the script

1. Interactive execution

[root@localhost ~]# for filename in `ls /etc`
> do
> if echo "$filename" | grep "passwd"
> then
> echo "$filename"
> fi
> done

2. Execute as a program file (commonly used)

For a group of shell statements that need to be executed repeatedly, save them in a file and execute them. This file containing multiple shell statements is called a shell script. A shell script file is an ordinary text file that can be edited by any text editor. view or modify shell scripts

mkdir /test
cd /test
vim test1.sh
for filename in `ls /etc`
do     
    if echo "$filename" | grep "passwd"
    then 
        echo "$filename"
    fi
    done

Five, the method of executing the script

1.bash ./filename.sh generates a child process, and then runs it, using the currently specified bash shell to run

2. ./filename.sh generates a child process and then runs it, using the shell specified in the script to run, using this method requires x permission

3. The source ./filename.sh source command is a shell internal command. Its function is to read the specified shell program file and execute all the statements in it in turn. It does not create a new subshell process, so the variables created in the script will be Save to the current shell

4. ./filename.sh  

Chapter 2 Variables and References

1. The type of variable

  • Classification by data type

The shell is a dynamically typed language and a weakly typed language. The data type of variables will change according to different operations, that is, variables in the shell are regardless of data type.

Weakly & Strongly Typed Languages

  • Strong typing: Once a variable is defined, its type is fixed and cannot be changed
  • Weak type: the type of the variable is not fixed and can be changed arbitrarily

Related operations for defining variables with declare:

-p: display the value of all variables

-i: Define the variable as an integer, and then evaluate the expression directly, and the result can only be an integer

-r: Declare the variable as a system variable, modification/deletion is not allowed

-a: declare the variable as an array variable

-f: Display all custom functions, including name & function body

-x: Set the face change as an environment variable, you can use +x to change the variable into a non-environment variable

  • Classification by scope

Can be divided into environment variables (global variables) and ordinary variables (local variables)

1. Environment variables: can be called global variables, and can be used in the shell that created them and any sub-process shell derived from them (su - switching users will read new environment variables), and environment variables can be divided into custom environments variables and bash built-in environment variables

(1) Custom environment variables

User's environment variable configuration (non-login shell), ~/.bash_profile or ~/.bashrc

Configuration of global environment variables (login shell), defined in /etc/bashrc, /etc/profile file or /etc/profile.d directory

(2) Bash built-in environment variables

The built-in environment variables of the shell are variables that can be used in all shell programs, and the environment variables will affect the execution results of all scripts.

2. Ordinary variables: called local variables. Compared with global variables, local variables have a smaller scope of use and are limited to access in a certain program segment. Function parameters are also called local variables

2. Definition of variables

1. Example of variable definition: variable name = variable value

Notice:

(1) There can be no spaces before and after "="

(2) The string type is enclosed in parentheses

Reference variable: $variable name or ${variable name}

View variables: echo $ variable name, set (you can view all variables: including custom variables and environment variables), env displays global variables, declare outputs all variables, functions, integers and exported variables

Unset variable: unset variable name

Scope of action: valid only in the current shell

2. Positional parameters and predefined variables

The shell script needs to perform different operations according to different parameters entered by the user

The parameters passed to the shell script from the command line are called positional parameters, and the shell script uses different positional parameter variables to read their values ​​​​according to the position of the parameters

variable illustrate
$# The number of command line arguments
$n Represents the nth parameter passed to the script, such as $1 represents the first
$0 the name of the current script
$* Return all values ​​(whole) in the form of "parameter1 parameter2"
$@ Return all values ​​in the form of "parameter1" "parameter2" (separated)
$? The return status code of the previous command or function, $? Usage of return value: 1. Judging whether the program such as command, script or function is executed successfully 2. If exit is called and executed in the script, this number will be returned to $? variable
$$ Returns the process ID of this program
$! Get the last process ID working in the background
$_ Save the last parameter of the command executed before

3. Quotes in the shell

symbol illustrate
escape character "\" When placed before special characters, the shell ignores the original meaning of these characters and outputs them as ordinary characters
apostrophe When a string is placed before single quotes, the special meaning of all characters in the string is ignored
Double quotes Same as single quotes, there are still some special characters that retain their own special meanings, such as "$", "\" and "`"

Tips: The strings in backticks will be interpreted as shell commands, the statements in single quotes will be output unchanged, and the sentences in double quotes still have the meaning of special characters  

Fourth, the operation of variables

  • Operators and Descriptions

operator illustrate
+ - sum, difference
* / % find product, quotient, remainder
** Power operation, 3**3 is to find the cube of 3
+= -= *= /= %= Monocular operation
++variable --variable add/subtract before assigning
bitwise operator <<>>

For the binary system, 2>>1, the binary form of 2, that is, 10 is shifted to the left by 1 bit, which becomes 100; 4<<2, the 100 is shifted to the left by two bits

& | ~ ^ Bitwise AND, 8&4, perform bitwise AND operation of 8 and 4, and the result is 0; bitwise OR, 8|4, perform bitwise OR operation of 8 and 4, and the result is 12; bitwise NOT, ~ 8, perform bitwise NOT operation on 8, the result is -9; bitwise XOR^
<<= >>= Shift the value of the variable to the left by the specified number of digits and reassign it to the variable, x<<3, shift the value of x to the left by 3 bits and reassign it to the variable x; shift the value of the variable to the right by the specified number of digits and then reassign it to the variable x
&=    |=    ^= Reassign the value of the variable and the specified value to the variable after the bitwise AND, x&=8, that is, assign the value of the variable x and 8 to the variable x
Operators and Arithmetic Commands significance illustrate
let for integer arithmetic Use the let command to execute one or more arithmetic expressions, and the variable name does not need to use the $ symbol
expr Can be used for integer arithmetic When using expr, there must be spaces on both sides of the operator or the number to be calculated, otherwise an error will be reported; when using the multiplication sign, use a backslash to shield its specific meaning; using expr to do calculations, you can add an unknown variable to a known integer , to see if the return code is 0, if yes, then it can be determined that the data type of the unknown variable is an integer, otherwise it is not an integer
bc a calculator program
$[] 用于整数运算
awk 用于小数、整数运算
declare 定义变量值和属性,-i参数可用于定义整型变量做运算
(()) 用于整数运算的常用运算符 在(())中使用变量时可去掉变量前的$符号
  • 变量相关的表达式

表达式 说明
${parameter} 返回变量的内容
${#parameter} 返回变量内容的长度(按字符)
${paramater:offset}

在变量${parameter}中从offset之后开始提取子串到结尾

${paramater:offset:length} 在变量${parameter}中,从位置offset之后开始提取长度为length的子串
${paramater#word} 从变量${paramater}开头开始删除最短匹配的word子串
${paramater##word} 从变量${paramater}开头开始删除最长匹配的word子串
${paramater%word} 从变量${paramater}结尾开始删除最短匹配的word子串
${paramater%%word} 从变量${paramater}结尾开始删除最短匹配的word子串
${paramater:/pattern/string} 使用string代替第一个匹配的pattern
${paramater//pattern/string} 使用string代替所有匹配的pattern

Guess you like

Origin blog.csdn.net/AChain1117/article/details/125794762