linux The control of the system is controlled by the kernel to allocate resources ,shell Commands are tools for communicating with kernel operations .shell There are many types of , common /bin/sh、/bin/bash, stay centos Environment By default bash, Other forms of... Are not recommended shell.
1) Historical record
bash shell When use , It will automatically record the command operated , The records are kept in .bash_history In file . Recent naming history 1000 strip , Can pass profile Set up HISTSIZE Adjust the length of the record , For example, you can set the number of records to 10000 /HISTSIZE=10000. When querying a used command , have access to Ctrl+r The shortcut key opens the command search , But in daily management, it is recommended to use history or history|grep xxxx Command find .
2) Shortcut key
In command line shell interface , The command line can use the following shortcut keys , Improve operation efficiency .
Ctrl+a Move the cursor to the beginning of the line
Ctrl+e Move the cursor to the end of the line
Ctrl+l Clear the screen
Ctrl+c Terminate the process
Ctrl+z Suspend process
Ctrl+u Delete the character from the cursor to the beginning of the line
Ctrl+k Delete the characters from the cursor to the end of the line
Ctrl+f Move the cursor one character to the right
Ctrl+b Move the cursor one character to the left
Ctrl+w Delete the character before the cursor
Alt+d Delete the character after the cursor
Tab Automatic completion
3) The alias set
linux Allow users to set the alias of the command according to their own needs . such as ,ll The command is 'ls -l --color=auto' Abbreviation , Alias complex commands , It can improve the efficiency of operation . Enter... In the command line interface alias You can view the command aliases that have been set ; For example, setting an alias : alias nginxstart='systemctl start nginx',nginxstart You can start it directly nginx 了 ; Remove alias :unalias nginxstart.
[root@centos7 yum.repos.d]# alias nginxstart='systemctl start nginx'
[root@centos7 yum.repos.d]# alias
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias nginxstart='systemctl start nginx'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
[root@centos7 yum.repos.d]# unalias nginxstart
4) Pipe, ---“|”
The pipe character is used to connect multiple commands , The result of the previous command is standard output to the standard input of the next command . for example ,cat /etc/passwd |grep bash Commands can be filtered out to have bash Users with login rights , direct cat see passwd When it comes to documentation , There is a lot of output , Inconvenient to view with bash Permission information , When you add pipes | after , Then use grep Command filtering cat Output information , Finally, it was screened out with bash Information line of .
5) Redirect ---“> ,>>”
The function of the redirection symbol is to output the result of the command to the specified file or location .> It's mandatory coverage mode , No file will automatically create a file , Documents , File contents will be overwritten ;>> Is append mode output to file ; The number at the end of the command also has a special meaning ,0 For standard input ,1 For standard output ,2 Represents standard error ;2>&1 To redirect standard error to standard output ;> /dev/null It's writing output to an endless black hole , The processing of user's uninteresting information .
[root@centos7 ~]# history > /tmp/1.txt
[root@centos7 ~]# cat /etc/nginx.conf >>/tmp/1.txt
[root@centos7 ~]# nohup ./rmlog.sh > rm.log 2>&1 &
[root@centos7 ~]# sh mysql.sh >/dev/null 2>&1
6) Sequence controller ---“&”
& yes shell The characters commonly used in , Add... After an order &, It means running in the background ;&& Can connect two commands , It means that only if the current command is successfully executed, the following command will be executed ;|| It means that when the previous command fails to execute, the following character will be executed .
[root@centos7 ~]# nohup /home/jiankong.sh & # The background does not interrupt the execution
7) quotes
Single quotation marks can be used to restore the literal meaning of a character , The function of shielding metacharacter is realized , Single quotation marks must be used in pairs ; Double quotation marks are basically the same as single quotation marks , But it doesn't block $ ' \ The function of these three metacharacters , If you want to block , It has to be preceded by a \; Backquotes are command substitution , Replace the command character with the command result output .
[root@centos7 ~]# echo '$JAVA_HOME' # To achieve shielding $ Special features of
[root@centos7 ~]# echo 'cd \home' # Implementation of shielding escape characters
[root@centos7 ~]# echo "$JAVA_HOME" # Double quotation marks output variables directly
[root@centos7 ~]# echo "\$JAVA_HOME" # use \ escape , Directly output the following characters
[root@centos7 ~]# echo "today is `date`" # Direct output date Results of command
8) Variable
Variables have environment variables 、 Common variables 、 Special variables . Environment variables generally refer to system environment variables , Just include the user 、 Catalog 、 route 、 Global parameters, etc , They need to execute export Statement can be used only , use env The command can view these variables . Ordinary variables are mainly the assignment of parameters to be called by the application . The special variable is linux Specific parameter variables set by the system . In daily application, the most important thing is to declare environment variables , Assignment variables are also used in scripts , Special variables are used less . Here are examples of three variables .
java Example of setting environment variables
[root@centos7 ~]# vim /etc/profile
JAVA_HOME=/usr/local/java
JRE_HOME=/usr/local/java/jre
CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME JRE_HOME CLASS_PATH PATH
[root@centos7 ~]# source /etc/profile
Examples of commonly used assignment variables in scripts
[root@centos7 ~]# starttime=`date`
[root@centos7 ~]# gameuser="lixiaoming"
[root@centos7 ~]# fr_1='12315'
Definition of special variables
$0 Get script file name
$n For the first n Parameter values ,$1 Is the first parameter ,$2 It's the second parameter ...
$# Get the total number of parameters
$* Get the parameter passed ,"$*" Represents the parameter as a single string , With "$1 $2 ... $n" Formal output parameters
$@ Get the parameter passed ,"$@" Indicates that the parameter is treated as a separate string , With "$1" "$2" "$3" ... "$n" Formal output parameters
$? Gets the execution status of the previous command ,0 It means success , Others are failures
$$ Get the process number of the current script or command
$! Get the process number of the last background process
9) Array
Array is a data structure with variable function , An array consists of elements , Each element is assigned a zero based integer index . There are two ways to define an array , One is to assign values one by one , Such as TESTA[0]=100,TESTA[1]=200; The other is to create a full value assignment , Such as TESTB=(12 23 34 45), Take the value of $TESTB[1]. Use the following example to deepen your understanding of arrays .
root@centos7 ~]# TESTB=(12 23 34 45) # Define a new array
[root@centos7 ~]# echo ${TESTB[2]} # The output index is 2 The element value of
[root@centos7 ~]# TESTB[4]=56 # Add the index to 4 New elements of
[root@centos7 ~]# echo ${TESTB[@]} # Output all elements , Space separates the element value format
[root@centos7 ~]# echo ${TESTB[*]} # Output all elements , String format
[root@centos7 ~]# echo ${#TESTB[@]} # The number of elements in the output array
[root@centos7 ~]# echo ${#TESTB[*]} # The number of elements in the output array
[root@centos7 ~]# TESTC=(${TESTA[@]} ${TESTB[@]}) # Two arrays are merged into a new array
10) Arithmetic operations
Bash Supports many operators , Including arithmetic operators 、 Relational operator 、 Boolean operator 、 String operators and file test operators .
1 Arithmetic operations
Native bash Simple mathematical operations are not supported , But it can go through expr Command to implement expr Is an expression calculation tool , It can complete the evaluation of expressions
a=10
b=20
Common arithmetic operators
+ Add `expr $a + $b` The result is 30
- Subtraction `expr $a - $b` The result is 10
* Multiplication `expr $a \* $b` The result is 200
/ division `expr $b / $a` The result is 2
% Remainder `expr $b % $a` The result is 0
= assignment a=$b Will put the variable b The value is assigned to a
== equal Used to compare two numbers , Same returns true,[ $a == $b ] return false
!= It's not equal Used to compare two numbers , If not, return to true,[ $a != $b ] return true
Be careful : Conditional expressions should be placed between square brackets , And there should be spaces , for example [$a==$b] It's wrong. , Must be written as [ $a == $b ]
2 Relational operator
Operator explain give an example
-eq Check whether two numbers are equal , Equal return true [ $a -eq $b ] return false
-ne Check whether two numbers are equal , Unequal return true [ $a -ne $b ] return true
-gt Check whether the number on the left is greater than that on the right , Is to return true [ $a -gt $b ] return false
-lt Check whether the number on the left is less than that on the right , Yes, go back to true [ $a -lt $b ] return true
-ge Check whether the number on the left is greater than that on the right , Yes, go back to true [ $a -ge $b ] return false
-le Check whether the number on the left side is less than or equal to that on the right side , Yes, go back to true [ $a -le $b ] return true
3 Boolean operator
Operator explain give an example
! Non operation , Expression for true Then return to false, Otherwise return to true [ ! false ] return true
-o Or operations , There is an expression for true Then return to true [ $a -lt 20 -o $b -gt 100 ] return true
-a And operation , Both expressions are true To return to true [ $a -lt 20 -a $b -gt 100 ] return false
4 String operators
Operator explain give an example
= Checks if two strings are equal , Equal return true [ $a = $b ] return false
!= Checks if two strings are equal , Unequal return true [ $a != $b ] return true
-z Check if the string length is 0, by 0 return true [ -z $a ] return false
-n Check if the string length is 0, Not for 0 return true [ -n $a ] return true
str Check if the string is empty , Not empty return true [ $a ] return true
5 File test operators
The operator explain give an example
-b file Check if the file is a block device file , If it is , Then return to true [ -b $file ] return false
-c file Check whether the file is a character device file , If it is , Then return to true [ -b $file ] return false
-d file Check if the file is a directory , If it is , Then return to true [ -d $file ] return false
-e file Detect the existence of files or directories , If it is , Then return to true [ -e $file ] return true
-f file Check if the file is a normal file , If it is , Then return to true [ -f $file ] return true
-g file Check if the file is set SGID position , If it is , Then return to true [ -g $file ] return false
-h file Check if the file is a linked file , If it is , Then return to true [ -h $file] return false
-k file Check whether the file is set with the adhesive bit ( If it is , Then return to true [ -k $file ] return false
-p file Check whether the file is a named pipe , If it is , Then return to true [ -p $file ] return false
-u file Check if the file is set SUID position , If it is , Then return to true [ -u $file ] return false
-r file Check whether the file is readable , If it is , Then return to true [ -r $file ] return true
-w file Check whether the file is writable , If it is , Then return to true [ -w $file ] return true
-x file Check if the file is executable , If it is , Then return to true [ -x $file ] return true
-s file Check if the file is not empty , Not empty , return true [ -s $file ] return true
11) The basis of regular expression
1 Regular common command tools
grep、egrep、sed、awk
2 The basic regular expression of symbolic meaning
d Match the letter d
. Match any single character
* Match one or more
.* Match any number of characters
^ Match the beginning of the string
$ Match the end of the string
[] Matches any single character in the set
[^] Match negation , Negate the set in brackets
[x-y] matching x To y Continuous string ranges
\ Match the escaped string
\{n,\} Match the previous character and repeat at least n Time
\{n\} Match the previous character and repeat n Time
\(\) call \( and \) Content between
3 Expression for check character
1 Chinese characters : ^[\u4e00-\u9fa5]{0,}$
2 English and numbers : ^[A-Za-z0-9]+$ or ^[A-Za-z0-9]{4,40}$
3 The length is 3-20 All characters of : ^.{3,20}$
4 from 26 A string of English letters : ^[A-Za-z]+$
5 from 26 A string of uppercase letters : ^[A-Z]+$
6 from 26 A string of lowercase letters : ^[a-z]+$
7 By numbers and 26 A string of English letters : ^[A-Za-z0-9]+$
8 By digital 、26 A string of English letters or underscores : ^\w+$ or ^\w{3,20}$
9 chinese 、 english 、 Numbers include underscores : ^[\u4E00-\u9FA5A-Za-z0-9_]+$
10 chinese 、 english 、 Number but excluding symbols such as underscores : ^[\u4E00-\u9FA5A-Za-z0-9]+$
11 Can be entered with ^%&',;=?$\" Equal character : [^%&',;=?$\x22]+
12 Disable input containing ~ The characters of : [^~\x22]+
4 Expression of special requirements
Email Address : ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
domain name : [a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
InternetURL: [a-zA-z]+://[^\s]* or ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$
Phone number : ^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$
Phone number ("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX" and "XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$
Domestic phone number (0511-4405222、021-87888822): \d{3}-\d{8}|\d{4}-\d{7}
15 or 18 position ×××: ^\d{15}|\d{18}$
15 position ×××: ^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$
18 position ×××: ^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$
short ××× number ( Numbers 、 Letter x ending ): ^([0-9]){7,18}(x|X)?$ or ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$
Is the account number legal ( Beginning of letter , allow 5-16 byte , Allow alphanumeric underscores ): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$
password ( Start with a letter , The length is in 6~18 Between , Can only contain letters 、 Numbers and underscores ): ^[a-zA-Z]\w{5,17}$
Strong password ( Must contain a combination of upper and lower case letters and numbers , Special characters cannot be used , The length is in 8-10 Between ): ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
Date format : ^\d{4}-\d{1,2}-\d{1,2}
One year 12 Months (01~09 and 1~12): ^(0?[1-9]|1[0-2])$
A month 31 God (01~09 and 1~31): ^((0?[1-9])|((1|2)[0-9])|30|31)$
tencent QQ Number : [1-9][0-9]{4,} ( tencent QQ Number from 10000 Start )
China Post Code : [1-9]\d{5}(?!\d) ( China Post code is 6 Digit number )
IP Address : \d+\.\d+\.\d+\.\d+ ( extract IP Useful for addresses )