Compile-language:
The program needs a special compilation process before execution, which compiles the program into a machine language file, the runtime does not need to be re-translated, the results of the direct use of the compilation is OK. The program executes efficiently, relies on the compiler, the cross-platform is inferior. such as C, C + +
Interpreted language:
The program does not need to be compiled, and the program is translated into machine language by the interpreter at run time, once every execution. Therefore, the efficiency is lower. such as Python/javascript/perl/ruby/shell are interpreted language.
Summarize:
Compiled languages are faster than interpreted languages, but they are not as good as the cross-platform of interpretive languages. In the case of low-level development or large-scale application or operating system development is generally used in the compiled language, if it is some server scripts and some auxiliary interfaces, the speed requirements are not high, the compatibility of the various platforms are generally interpreted language.
What does the Linux operating system consist of?
Kernel, shell, application, file system
Shell: A Bridge of command interpreter man-machine interaction
Terminal--"command
|
Bash Shell interpreter (shell)
|
Kernel
|
Hardware
What is a shell script?
In a nutshell, save the command you want to execute in the text, and execute it in order. It is interpreted, meaning it does not need to be compiled.
Basic formatting of several commands + scripts + Script-specific syntax + thought = Shell script
When do I use a script?
Repetitive, complicated work, by writing the commands of the work into scripts, and then just executing the script to complete the work.
How do I learn scripts?
1, as far as possible to remember more commands
2. Master the standard format of the script (Specify the Magic byte, run the script using the standard execution mode)
3, must be familiar with the basic syntax of the script (the following list is only the basic requirements, there are a lot of deeper and more difficult grammar need to expand their own learning)
Variable definition
Conditional judgment
Branch statements
Function
Array
Looping statements
Regular expressions
Use of the Sed,awk command
Tips for Learning Scripts:
Read more, write more, think more
Read script--and copy--write
How to write scripts:
Non-standard:
SOURCE xxx.sh
. xxx.sh
Bash xxx.sh
SH xx.sh
Standard:
The format is a relatively complete script, recommended format.
#!/bin/bash the first line of the script, #! the magic character, specifying the script code to execute the program. That is, it tells the system what interpreter the script needs to execute, that is, which shell to use
Name: Desc: Description Describepath: Store path Usage: Usage update: Update time
。。。。
Script Execution methods:
Standard script execution methods (recommended): (magic bytes The specified program will take effect)
Non-standard execution method (not recommended): (Magic byte specified program does not work)
Summarize:
./xxx.sh-Requires execute permission, and be sure to declare shell type (#!/bin/bash)
. xxx.sh or source xxx.sh or bash xxx.sh or sh xxx.sh--no execution permission required, or shell type not declared
Description: Bash-x xxx.sh or Sh-x xxx.sh--can show the execution process, help the troubleshooting
Add:
Quotes in bash:
Double quotes "" will look at the contents of the quotation marks as a whole, allowing other variable values to be referenced by the $ symbol
Single quotes ' will treat the contents of the quotation marks as a whole, prohibit referencing other variable values, and the special symbols in the shell are treated as ordinary characters
The anti-apostrophe ' and $ () anti-apostrophe and the parentheses in the command are performed preferentially, and if nested, the inverse apostrophe is not available.
; You can split a single line of commands, regardless of whether the last command execution is correct during execution
&& logic and. You can split a row of commands to consider whether the last command execution was correct during execution
|| Logical OR
Categories of variables:
Local variable: The current user-defined variable. The current process is valid, and the other processes and child processes of the current process are not valid.
unset a Cancel variable
Environment variable: The current process is valid and can be called by the quilt process.
Hi=hello setting a local variable
View environment variables for the current user env
Env |grep HI
Querying all variables < temp variables and environment variables for the current user >
Set |grep HI
Hi=hello
Export HI To change the current variable to an environment variable
Env |grep-i HI
histsize=1000
Hi=hello
Global variables: All users and programs in the global can be called and inherited, and new users can call them by default.
/etc/profile
Hi=hello
Export HI
/etc/profile
/etc/bashrc
~/.bash_profile
~/.bash_bashrc
User-->login-->/etc/profile-->~/.bash_profile-->/etc/bashrc-->~/.bashrc-->~/.bash_logout
Local variables:
~/.bash_profile
...
Note: Re-login is required to take effect
$HOME/.BASHRC Current user fixed variable eg: Alias
$HOME/.bash_profile Environment variables for the current user
/ETC/BASHRC using bash shell user global variables
/etc/profile using global variables for all shells
System variables (built-in bash variables): The shell itself has its name and function fixed. [Email protected],$*,$#, $$, $?] , $
$#: Number of parameters followed by the script
$*: All parameters behind the script
[Email protected]: All parameters behind the script
$?: The state returned after the previous command was executed, when the return status value is 0 indicates normal execution, and a value other than 0 indicates an exception or error
If the exit status value is 0, the command runs successfully
If the exit status value is 127 command not found
If the exit status value is 126 and the command is found but cannot be performed---permissions are insufficient
If the exit status value is 1&2 there is no file or directory
$$ the process number of the current process
$! The last process number running in the background (current terminal)
!$ calls the arguments in the last command history
!! Call the last command history
The currently executing process/program name
$1~$9 Positional parameter variables
${10}~${n} extension positional parameter variable 10th position variable must be enclosed in {} braces
Vim 3.sh
#!/bin/bash
#xxxxx
echo "\$0 = $"
echo "\$# = $#"
echo "\$ = $"
echo "\[email protected] = [email protected]"
echo "\$1 = $"
echo "\$2 = $"
echo "\$3 = $ $"
echo "\$10 = ${10}"
When do I use a variable?
If a content needs to be used more than once and is repeated in code, you can use a variable to represent that content. So when you modify the content, you just need to modify the value of the variable
In the process of code operation, it is possible to save the results of some commands, subsequent code needs to use these results, you can directly use this variable
Rules for variable definitions:
1, by default, the variables defined in the shell are non-typed, you can assign the variable to any type of value; there can be no spaces on either side of the equals sign, and when you assign a string with a space, enclose it in quotation marks.
955 A=hello
956 Echo $A
957 a= Hello
958 A =hello
959 A = Hello
960 A=hello World
961 a= ' Hello World '
962 Echo $A
963 a= "Hello World"
964 Echo $A
2. How to get the variable: $ variable name ${variable name}
966 Echo $A
967 Echo ${a}
968 a=123456
969 Echo $a
970 Echo ${a}
971 Echo ${a:2:3}
972 a=123456789
973 Echo ${a:3:5} 3 represents the Intercept from the 3rd position; 5 means 5 numbers
975 Echo ${a:3} represents interception from the beginning of the 3rd bit after all
3. The unset variable name of the command to cancel the variable
4, case-sensitive, the same name but different case of variable names are different variables
5. Variable names can be letters or numbers or underscores, but cannot start with a number or special characters
[Email protected] shell01]# A=1ABC
[Email protected] shell01]# 1a=hello
Bash:1a=hello:command not found
[email protected] shell01]#? a=hello
BASH: A=hello:command not found
[Email protected] shell01]#/a=hello
BASH:/a=hello:no such file or directory
[Email protected] shell01]# _a=777
[Email protected] shell01]# echo $_a
777
6, the execution result of the command can be saved to the variable
Attention:
$ () equivalent to execute symbol`,But if you want to use them in nest, you can't use symbols. You need to use $ (); but if you don't use them in nest, such as a="which Mount`which yum"
7. Arrays
Array definition: The array is represented by parentheses, and the elements of the array are separated by a "space" symbol. The general form of the definition array is:
array= (var1 var2 var3 VAR4)
Or
Array[0]=v1
Array[1]=v2
Array[3]=v3
To read an array:
${array [i]} I represents an element
Use @ or * to get all the elements in the array:
Hello,stu1
Hello,stu2
Hello,stu3
#!/bin/bash
array= (stu1 stu2 stu3)
For Var in ${array[*]}
Do
echo Hello, $var
Done
[Email protected] shell01]# Var[0]=user1
[Email protected] shell01]# Var[1]=user2
[Email protected] shell01]# Var[2]=user3
[[email protected] shell01]# for I in ${var[@]};d o echo Hello, $i;d One
Hello,user1
Hello,user2
Hello,user3
Gets the nth element
echo "${user[n-1]}"
Gets an array of specified elements
Echo ${user[@]:1:3} starts with array subscript 1 and reads 3 elements
Example:
Defines a set of user u01~u05 that are displayed on the screen separately hello,username
8. Variable with type
Declare
-I treat variables as integers
-r make variable read-only readonly
-X Tag variable exported through environment export
-A variables as arrays
[Email protected] shell01]# a=10
[Email protected] shell01]# b=2
[Email protected] shell01]# c= $a + $b
[Email protected] shell01]# echo $c
10+2
[Email protected] shell01]# declare-i a=5
[Email protected] shell01]# declare-i b=2
[Email protected] shell01]# declare-i c= $a + $b
[Email protected] shell01]# echo $c
7
[Email protected] shell01]#
[Email protected] shell01]# declare-i a=10 b=2
[Email protected] shell01]# declare-i c= $a * $b
[Email protected] shell01]# echo $c
20
1040 Echo $a
1041 Declare-r A=hello
1042 Echo $a
1043 Declare-r A=hello
1044 a=888
1045 Echo $A
1046 Declare-i a=123
1047 Ab=hello
1048 Export AB
1049 Env|grep AB
1050 Declare-x Abc=hahaha
1051 Env|grep ABC
9. Interactively define the value of the variable read is primarily used to allow the user to define the value of the variable
-p hint Information-n characters-S does not display-t timeout (default unit seconds) Read-t 5 A
1054 Read-p "Input your name:" Name
1055 Echo $name
1056 Read-s-P "Input Your password:" Pass
1057 Echo $pass
1058 read-n 5-p "Input Your name:" Name
1059 Echo $name
1060 read-t 3-p "Input Your name:" Name
1061 Echo $name
1062 read-t 3-p "Input Your name:" Name
1063 Echo $name
10. Other variables:
A "#" means to remove a specified character from left to right
Two "#" represents the maximum left to right to remove the specified character
A "%" means to remove a specified character from right to left
Two "%" means to remove the specified character from the right-to-left maximum
Remove directories and files from a directory
A=/root/desktop/shell/mem.txtecho $A
/root/desktop/shell/mem.txt
DirName $A Removing the directory
/root/desktop/shell
basename $A Take out files
Mem.txt
Echo ${a%/
} Remove from right to left "/The content
/root/desktop/shell
Echo ${a%%.
Remove from right to left maximum length.After the content
/root/desktop/shell/mem
Echo ${a%%.txt} remove. txt content from right to left maximum length
/root/desktop/shell/mem
Echo ${a##/
/} from left to right max remove all "//"
Mem.txt
Echo ${a#/*/}
Desktop/shell/mem.txt
1071 Aaa=/shell/shell01/dir1/file.txt
1072 Echo $AAA
1073 DirName $AAA
1074 basename $AAA
1075 Echo ${aaa#/*/}
1076 Echo ${aaa##/*/}
1077 Echo ${aaa%.*}
1078 Echo ${aaa%%.*}
1079 Echo ${aaa%/*/}
Echo ${aaa%/*}
1081 Echo ${aaa%%/*}
= = = Variable Content replacement = = =
[Email protected] desktop]# a=www.taobao.com
[[email protected] desktop]# echo ${a/taobao/baidu}
Www.baidu.com
[Email protected] desktop]# a=www.taobao.com
[[email protected] desktop]# echo ${a/a/a}
Www.tAobao.com
[[email protected] desktop]# echo ${a//a/a} greedy replacement
Www.tAobAo.com
= = = Variable substitution = = =
Echo ${VAR1-AAAAA}
Aaaaa
Var2=111echo ${VAR2-BBBBB}
111
Var3=echo ${VAR3-CCCCC}
${variable Name:-New Variable Value}
Variables are not assigned (including null values): will be replaced with "New variable value"
Variable has been assigned: will not be replaced
Simple arithmetic.
Arithmetic operations:
By default, the shell can only support simple integer operations
-
-
- /% (modulo, to find remainder)
$(()) | $[] | Expr | Let
There are four ways in which the Bash Shell's arithmetic operations are:
1. Use $ (())
2. Use $[]
3. Using Expr external program
4. Using the Let command
Addition:
n=10
Let N=n+1
or let N+=1
Echo $n
Multiplication:
Let m=n*10
Echo $m
Division:
Let R=M/10
Echo $r
To find the remainder:
Let R=m%7
Echo $r
By emerges:
Let R=m**2
Echo $r
Attention:
N=1
Let n+=1 equivalent to let n=n+1
Think: Can you use the shell to do a small number of operations?
Echo 1+1.5|BC
2.5
i++ and ++i (Learn)
Effect on the value of the variable:
[Email protected] desktop]# I=1
[[email protected] desktop]# let i++
[Email protected] desktop]# echo $i
2
[Email protected] desktop]# j=1
[[email protected] desktop]# let ++j
[Email protected] desktop]# echo $j
2
Effects on the value of an expression:
[Email protected] desktop]# unset i J
[Email protected] desktop]# I=1
[Email protected] desktop]# j=1
[[email protected] desktop]# let x=i++ first assignment, then arithmetic
[Email protected] desktop]# echo $i
2
[Email protected] desktop]# echo $x
1
[[email protected] desktop]# let Y=++j first operation, then assign value
[Email protected] desktop]# echo $j
2
[Email protected] desktop]# echo $y
2
Conditional judgment
Syntax structure:
if [Condition];then
Command
Command
Fi
if [Condition];then
Command1
Else
Command2
Fi
if [Condition1];then
Command1 End
elif [Condition2];then
Command2 End
Else
Command3
Fi
If condition 1 satisfies, executes command 1 to end, if condition 1 is not satisfied, then see condition 2, if condition 2 satisfies execution command 2, if condition 1 and condition 2 do not satisfy execute command 3.
if [Condition1];then
Command1
if [Condition2];then
Command2
Fi
Else
if [Condition3];then
Command3
elif [Condition4];then
Command4
Else
Command5
Fi
Fi
If the condition 1 satisfies, executes the command 1, if the condition 2 also satisfies the execution command 2, if not satisfied, executes only the command 1 end;
If the condition 1 is not satisfied, do not look at the condition 2, directly see condition 3, if the condition 3 satisfies the execution command 3, if not satisfied then see condition 4, if the condition 4 satisfies the execution command 4;
Judgment syntax:
1. Test conditional expression
2. [Conditional expression]
3. [[conditional expression]] matches regular =~
Cat if3.sh
#!/bin/bash
Aaa=$1
[$aaa = ' Hello '] && echo World
[Email protected] shell01]# bash-x if3.sh
If3.sh:line 3: [: =: unary operator expected
[Email protected] shell01]# bash-x if3.sh Hello
-
Aaa=hello
-
' [' Hello = Hello '] '
- Echo World
World
[Email protected] shell01]# vim if3.sh
[Email protected] shell01]# bash-x if3.sh
Man test to see, a lot of parameters are used to determine the condition
and the existence or absence of a file
-E exists whether it is a file or a directory, as long as it exists, the condition is established
-F is a normal file
-D is a directory
-S socket
-P Pipe
-C character
-B Block
-L Soft Link
File permission-related judgments
-R whether the current user is readable
-W Whether the current user is writable
-X Whether the current user is executable
-U whether there is suid
-G whether Sgid
-K whether there is a T-bit
-S is a blank file description:-s means non-empty,! -S represents an empty file
[-S file1] file1 file content is not empty, the condition is set
[!-s File1] file1 file content is empty, condition established
Comparison of two files
File1-nt file2 Compare File1 is more than file2 new
File1-ot file2 Compare File1 is more than file2 old
File1-ef file2 comparison is the same file, or is used to determine whether a hard connection, point to the same inode
The judgment between integers
-eq equal
-ne Range
-GT Greater than
-lt less than
-ge greater than or equal to
-le less than or equal to
The judgment between the strings
-Z is an empty string string length of 0, it is established
-N is a non-empty string as long as the string is non-null, is set
string1 = string2 is equal
String1! = string2 Unequal
! Result inversion
Multiple conditional judgments
Logical judgment Symbol:
-A and && logic and [condition 1-A condition 2] Only two conditions are established, the whole condition is established.
[1-eq 1] && [2-ne 3]
[1-eq 1-a 2-ne 3]
-O and | | logical OR [conditional 1-o condition 2] as long as one of the conditions is established, the entire condition is established.
[1-eq 1-o 2-ne 2]
[1-eq 1] | | [2-ne 2]
! Lowest logical non-priority
-a priority is higher than the-O priority
Cat if4.sh
#!/bin/bash
Aaa=id -u
[$aaa-eq 0] && echo "Current is super user" | | echo "You are not Superuser"
[$ (Id-u)-EQ 0] && echo "Current is super user"
$ [$UID-eq 0] && echo "Current is super user" | | echo "You are not Superuser"
((1==2)); echo $? Numeric comparison of C-language styles ((1>=2)); echo $?
Demo1:
Determine if an IP is ping-through
Method 1:
#!/bin/bash
Read-p "Please enter the IP address you want to ping:" IP
PING-C1 $ip &>/dev/null or >/dev/null 2>&1
If [$?-eq 0];then
echo "Current host with the IP network entered OK"
Else
echo "The current host and the IP network entered are not OK"
Fi
Method 2:
PING-C1 $ &>/dev/null
Test $? -ne 0 && Echo "The current host is not OK with the IP network entered" | | echo "Current host with the IP network entered OK"
Demo2:
Determine if a process exists
1. Ps-ef|grep vsftpd |grep-v grep
2. Pidof Program Name
3. Pgrep-l Program Name
#!/bin/bash
Ps-ef|grep vsftpd|grep-v grep &>/dev/null
If [$?-eq 0];then
echo "The process exists"
Else
echo "The process does not exist"
Fi
Read-p "Please enter the process name you need to judge:"
Pidof $name &>/dev/null
[$?-eq 0] && echo "The process exists" | | echo "The process does not exist"
Pidof $ &>/dev/null
Test $? -ne 0 && echo "This process does not exist" | | echo "The process exists"
Requirements: Use this script to determine if the entered process exists (multiple process names, at least 2)
#!/bin/bash
[$#-eq 0] && echo "This script is used by: $ pidname" | | Pidname= ($*)
For i in ${pidname[@]}
Do
Pidof $i &>/dev/null
Test $? -ne 0 && echo "This process does not exist" | | echo "The process exists"
Done
Pgrep command: Finds a process from the running process queue by name and displays the process ID found
Options
-O: Displays only the minimum (start) process number found;
-N: Displays only the maximum (end) process number found;
-L: Displays the process name;
-P: Specifies the parent process number; Pgrep-p 4764 view child process ID under parent process
-G: Specifies the process group;
-T: Specifies the terminal on which the process is opened;
-u: Specifies a valid user ID for the process.
DEMO3:
Determine if a service is normal (take httpd as an example):
1, can determine whether the process exists, using/ETC/INIT.D/HTTPD status to judge the state and other methods
2, the best way is to go directly to access, through the access to success and failure of the return value to determine
#!/bin/bash
WGET-P/tmp http://localhost &>/dev/null
[$?-eq 0] && echo "normal service" | | echo "This service is not working"
Classroom Exercises:
1, write a script to determine whether a user exists
2, the improvement of the previous script bug, the request when the script is not passed or the number of parameters is not equal to 1, the use of prompt script: usage:xxx.sh IP
#!/bin/bash
[$#-ne 1] && echo "Usage:basename $0username" && exit
ID $ &>/dev/null
Test $? -eq 0 && echo "The user exists" | | echo "The user does not exist"
#!/bin/bash
[$#-ne 1] && echo "Usage:basename $0ipaddr" && exit
wget http://$1 &>/dev/null
[$?-eq 0] && echo ' httpd service normal ' | | echo "httpd service is not working"
3, determine whether the VSFTPD package is installed, if not installed automatically
4, judge whether the VSFTPD service starts, if start, output the following information:
VSFTPD Server is started ...
The address of the VSFTPD listener is:
The ports that the VSFTPD listens on are:
#!/bin/bash
Ftp=vsftpd
Rpm-q $ftp &>/dev/null
[$?-ne 0] && yum-y install $ftp &>/dev/null
Pgrep-l $ftp &>/dev/null
[$?-ne 0] && service $ftp start &>/dev/null && echo "Services started ..."
ip=netstat -nltp|grep $ftp|cut -d: -f1|cut -c21-
port=netstat -nltp|grep $ftp|cut -d: -f2|cut -d‘ ‘ -f1
echo "VSFTPD listening address is: $ip"
echo "VSFTPD listening port is: $port"
Homework:
1, determine whether the/tmp/run file exists, if not exist on the establishment, if there is to delete all files in the directory
#!/bin/bash
Dir=/tmp/run
[-D $dir] && rm-rf $dir/* | | mkdir $dir
Dir=/tmp/run
[-F $dir] && mv $dir $dir. bak
[-D $dir] && rm-rf $dir/* | | mkdir $dir
2, enter a path to determine if the path exists, and whether the output is a file or directory, if it is a character connection, you also have to output a valid connection or invalid connection
#!/bin/bash
Read-p "Please enter absolute path:" Path
If [-E "$path"-a-l "$path"];then
echo "The file is a valid connection file"
elif [!-e "$path"-a-l "$path"];then
echo "The file is an invalid connection file"
elif [-D $path];then
echo "The file is a directory"
Elif [-F $path];then
echo "The file is a normal file"
elif [-E $path];then
echo "Other Files"
Else
echo "Path does not exist"
Fi
3, the interactive mode requires the input of an IP, and then the script to determine whether the IP corresponding to the host can ping, the output is similar to:
Server 10.1.1.20 is down! Finally request the result mail to the local administrator [email protected] and [email protected]
4, write a script/home/program, require when the script input parameter Hello, the script returns to the world, to the script input parameter world, the script returns hello. When the script has no parameters or parameter errors, the screen outputs "Usage:/home/program Hello or World"
#!/bin/bash
If ["$" = "Hello"];then
Echo World
elif ["$" = "World"];then
echo Hello
elif [$#-ne 1];then
echo "Usage:$0 Hello or World"
Else
echo "Usage:$0 Hello or World"
Fi
5. Write a script to automatically build NFS services
#!/bin/bash
#1. Installing the Software
#2. Verify that the software is installed
#3. Configuration
# (1). Create a new shared directory, Grant local permissions
# (2). Publish the shared directory/etc/exports
#4. Start the service
#5. Set the next boot auto-start
#配置网络, testing the network
Ping-c 1 192.168.0.254 &>/dev/null && echo "############# #网络OK ###############"
#配置network Yum
rm-fr/etc/yum.repos.d/*
Cat >/etc/yum.repos.d/dvd.repo << EOT
[Base]
Baseurl=ftp://192.168.0.254/rhel6_dvd
Gpgcheck=0
EOT
#1. Installing the Software
Yum-y Install nfs* rpcbind &>/dev/null && echo "############# #软件安装OK ###############"
#2. xx
#3. Configuration
# (1). Create a new shared directory, Grant local permissions
#read-P "Please enter your shared directory" dir
Mkdir-p $
chmod 777 $ && echo "############# #本地授权OK ###############"
No.3 shell Script