"13.1" What is shell script.
1 shell script is a "program" written using the function of the shell, which uses a text file to write some shell syntax and commands (including external commands) inside, with regular representations, pipeline commands, and data flow redirection, In order to achieve what we want to deal with.
1.1 To put it simply, shell script is like a batch file (. bat) in the early DOS era, and the simplest feature is to write many commands together so that the user can easily handle complex actions in one touch (running a file "shell Scri PT ", you can run more than one command at a time. and shell script provides important functions such as array, loop, condition and logic judgment, so that users can write the program directly in shell without using the syntax of traditional programming such as C programming language. 1.2 Shell script can be simply seen as a batch file, or it can be said to be a program language, and the program language is used by the shell and related Tools command, so do not need to compile to run, and have a good debugging tool, so, He can help the system administrator to quickly manage the host. 2 shell script used in the system management is a good tool, but used in processing a large number of numerical operations, it is not good enough, because the shell scripts slow, and the use of more CPU resources, resulting in poor allocation of host resources. Fortunately, we usually use shell script to handle the detection of the server, but there is no need for a large number of operations. So don't worry about it.
writing and executing the first script of "13.1.2"
1 Shell writing rules: In the shell script writing also need to use the following considerations:
1. The operation of the command is from the top down, from the left and right analysis and operation; 2. Orders are issued as mentioned in chapter Fifth: Multiple spaces between commands, options, and parameters are ignored; 3. The blank line is also ignored, and the white space pushed by the [tab] key is also treated as a blank key; 4. If read to a Enter symbol (CR), try to start running the line (or the string) command; 5. If there is too much content on a line, you can use "\[enter" to extend to the next line; 6. "#" can be annotated. Any data appended to the # will all be treated as annotation text and ignored. 2 Shell Execution mode: Let's say you wrote this file name is/home/dmtsai/shell.sh Well, then how to run this document. Quite simply, there are several ways to do this:
Direct command release: The shell.sh file must have readable and operational (RX) permissions, and then:
0 Absolute path: Use/home/dmtsai/shell.sh to release the command;
0 relative path: Assuming the working directory is/home/dmtsai/, use./shell.sh to run
0 variable "PATH" feature: Place shell.sh in the directory specified by path, for example: ~/bin/
Run in Bash program: Run with "bash shell.sh" or "sh shell.sh"
Add: Then why "sh shell.sh" can also be run. This is because/bin/sh is actually/bin/bash (link file), using the SH shell.sh that tells the system that I want to run directly to Bash's function to operate shell.sh the relevant command in this file, so your shell.sh as long as you have r right Limit can be run OH.
3 Write a 1th shell script
#!/bin/bash
# Program:
# This program shows ' Hello world! ' in your screen.
# History:
# 2005/08/23 Vbird-A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin
export PATH
echo-e "Hello world! \a \ n "
(1)
good habits of "13.1.3" writing shell script
1) suggest you must develop good script writing habits, in each script at the end of the file record well:
The function of the script;
Script version information;
The author and contact method of script;
The way of copyright declaration of script;
Script History (historical record);
Script more special commands, using the "absolute path" way to release;
The environment variables required by the script runtime are declared and set in advance.
"13.2" simple shell script exercises
"13.2.1" simple example
1 Interactive scripting: variable content is determined by the user
Please write a script using the Read command, which allows the user to enter: 1. The name of the 2. Last name, finally and on the screen: "Your full name is:" Content:
(2)
#!/bin/bash
# Program:
# User Inputs-his-name and last name. Program shows he full name.
# History:
# 2005/08/23 Vbird-A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin
export PATH
read-p "Please input your name:" FirstName # Prompts the user to enter
read-p "Please enter your last name: " LastName # Prompt the user for input
echo-e "\nyour full name is: $firstname $lastname" # knot Output by screen
2 Change with Date: Create a file using a date:
Let's say I want to create three empty files (through touch), the file name starts with the user input decision, assuming the user input filename well, today's date is 2009/02/14, I want the days before, yesterday, today's date to create these files, that is Filename_ 20090212, filename_20090213, filename_20090214, what to do is good.
[Root@localhost scripts]# vim sh03.sh
#!/bin/bash
# Program:
# program creates three files, which named By user ' s input
# and date command.
# History:
# 2018/05/01 Tang Rong the '
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin :/usr/local/sbin:~/bin
Export PATH
# 1. Let the user enter the file name and obtain the Fileuser variable;
echo-e "I'll use the ' Touch ' command t o Create 3 files. "# Pure Display information
read-p ' please input your filename:" Fileuser # Prompts the user to enter
# 2. To prevent users from pressing Enter at will, use the variable function to analyze whether the file name is configured.
filename=${fileuser:-"FileName"} # start to determine if there is a configuration file name
# 3. Start using the date command to obtain the required filename;
date1=$ (Date--date= ' 2 days ago ' +%y%m%d #
date2=$ (date--date= ' 1 time ago ' +%y%m%d) # day before date
date3=$ (Date +%y%m %d) # today's date
file1=${filename}${date1} # Three lines below the config file name
file2=${filename}${date2}
file3=${ Filename}${date3}
# 4. Create the file name. Touch "
$file 1" # The bottom three lines in the Create file Touch
"$file 2" Touch
"$file 3"
(3)
(4)
3) Numerical operation: Simple subtraction
If we want the user to enter two variables, then multiply the contents of the two variables, and then output the results of the multiplication, what can be done.
(5)
Add: Brother Bird it is recommended to use this method to perform the operation:
var=$ ((OP content))
Not only easy to remember, but also more convenient, because the two parentheses can add a blank byte oh. In the future you can use this method to calculate AH. As for numerical operations, there are: "+,-, *,/,%" and so on. That% is the remainder ~ For example, 13 to 3 to take the remainder, the result is 13=4*3+1, so the remainder is 1 ah. It is:
(6)
The "13.2.2" script performs differently (source, SH script,./script)
1 The script runs in addition to the method discussed in the previous section, you can also use source or decimal point (.) to run OH. So how does this work differently?
Mode 1) Execute script using direct execution method
When using the direct command release referred to in the previous section (either an absolute or relative path or a $PATH), or using bash (or SH) to release the script, it uses a new bash environment to run the commands within the script. In other words, when you use this mode of operation, the script is actually running in the subroutine bash.
The emphasis is: "When the subroutine completes, the variables or actions within the subroutine will end without being passed back into the parent program."
"Litchi" We have just mentioned that the sh02.sh this script can be used to allow users to configure two variables, respectively, FirstName and LastName, think about, if you run the command directly, the command to help you configure the FirstName will not take effect.
(7)
1.2 Using source to execute the script: executing in the parent process
(8)
"13.3" Use the judgment-style "13.3.1" to determine whether the directory exists by using the test function
1 of the Test Command
(9)
2) Then I know-e is to test a "thing" in the absence, if you want to If you want to test what the file name is, what other signs can be judged. Oh. There are these things underneath.
(Ten)
(one)
3) OK. Now let's use test to help us write a few simple examples. First of all, judge, let the user enter a filename, we judge:
Judge 1) whether the file exists, if it does not exist, give a "Filename does not exist" information, and interrupt the program; Judge 2 if the file exists, It is judged that he is a file or directory, the result output "filename is regular file" or "filename is directory"; Judge 3) to determine the rights of the runtime to the file or directory, and to output the rights data. ()
()
#!/bin/bash # Program: # User input a filename, program'll check the flowing: # 1. Exist? 2.) File/directory? 3.) file Permissions # History: # 2005/08/25 Vbird-i-Release path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin Export PATH # 1.
Let the user enter the filename and determine if the user really has an input string. ECHO-E "Please input a filename, I'll check the filename ' s type and \ permission." \ n \ nthe "read-p" input a filename: "filename test-z $filename && echo" You must Input a filename. "&& Exi T 0 # 2. Determine if a file exists. If it does not exist, display the information and end the script test! -E $filename && echo "The filename ' $filename ' does not exist ' && exit 0 # 3. Start to determine file types and attributes test-f $filename && filetype= "Regulare file" test-d $filename && filetype= "directory" test- R $filename && perm= "readable" test-w $filename && perm= "$perm writable" test-x $filename && per m= "$perm executable" # 4.
Start outputting information. echo "The filename: $filename is a $filetype" echo "and the PermissioNS are: $perm "
"13.3.2" using the judgment symbol []
1 In addition to the test we like to use, in fact, we can use the judgment symbol "[]" (that is, in parentheses) to make the data judgments. For example, if I want to know if $HOME this variable is empty, you can do this:
(14)
Add 1: If you want to use the bracket as the Shell's judgment in the syntax of bash, you must be aware that the ends of the brackets need to be separated by a blank byte.
2) Assuming that I use the "-" notation for the blank key, then you need a blank key in these places:
(15)
So, you'd better pay attention to:
Each component within the brackets [] needs to be delimited by a blank key;
The variables within the brackets are best bracketed with double quotes;
The constants within the brackets are best enclosed in single or double quotes.
"Litchi" using brackets [] to judge, the difference between quotes
(16)
"Litchi" then we also use the square brackets to do a small case of good, the case configuration is as follows:
1. When running a program, this program will let the user choose Y or N,
2. If the user enters Y or y, it displays "OK, continue"
3. If the user enters n or n, it displays "Oh, interrupt." 』
4. If not the other byte within the y/y/n/n, show "I don ' t know what your choice is"
Using brackets [], && and | | Let's go on.
(17)
default variable for "13.3.3" shell script ($, $ ...). )
1 If you want to restart the system login function, you can do this:
(18)
2 How does the script achieve this function? Actually, the script has some variable names configured for the parameters. Corresponds to the following:
(19)
3 In addition to these numbers of variables, we have some more special variables can be used in the script to invoke these parameters oh.
$#: Represents the "number" of the following parameters, the above table for example, shown here as "4";
$@: Represents "$" "$" "$" "$" meaning that each variable is independent (enclosed in double quotes);
$*: Represents "$1c$2c$3c$4", where C is a delimited byte, the default is a blank key, so this example represents "$ $ $ $" meaning.
"Litchi" Suppose I want to run a script that can carry parameters, and the screen will display the following data after running the script:
The file name of the program. There are several parameters. If the number of parameters is less than 2, the user is told that the parameters are too small. The first argument. The second argument.
(20)
3) Shift: The parameter variable number deviation is caused
The "Litchi" shift will move the variable, and the shift can be followed by a number, representing the first few parameters to take away.
(21)
"13.4" Conditional judgment type
"13.4.1" uses If...then
1 single-layer, simple conditional judgment: If you have only one judgment to proceed, then we can simply look at this:
(22)
1.1 If I have multiple conditions to distinguish, I can also have multiple brackets to separate OH. and between the brackets and the parentheses, the && or | | To separate, their meaning is:
&& representative and;
| | on behalf of OR;
1.2 So, in the use of square brackets in the judgment, && and | | It is different from the state of the command release. For example, the sh06.sh can be modified in this way:
["$yn" = = "Y"-o "$yn" = = "Y"]
The upper can be replaced with the
["$yn" = = "Y"] | | ["$yn" = = "Y"]
The reason for this change is that many people are accustomed to problems. Many people like a reason why brackets have only one discriminant.
"Litchi" will sh06.sh modified to look at the style of If...then:
(23)
2 multiple, complex conditions of judgment
2.1) A condition judgment
(24)
2.2) Multiple conditional judgments
(25)
Note: You have to pay attention to, Elif is also a judgment, so the appearance of elif after the then to deal with. But else is already the final result of no establishment, so else there is no then oh. Good. We're going to rewrite sh06-2.sh like this:
"Litchi" Change multiple IF statements to elif statements
(26)
3 in general, if you do not want users to enter additional data from the keyboard, you can use the parameter features mentioned in the previous section ($). Let the user bring the parameter in when the command is issued. Now that we want the user to enter the keyword "Hello", the method of using the parameter can be designed in this way:
1. To determine if it is hello, if so, show "Hello, how are you?" ;
2. If no parameters are added, the user must be prompted to use the parameters of the method;
3. If the added parameter is not hello, remind the user to use Hello only as a parameter.
The whole process can be written like this:
(27)
"Litchi" netstat command: query to the current host open Network service port
Litchi 1) I can use the "netstat-tuln" to get the current host has started service:
(28)
Add: The above focus is "local addresses (IP and port corresponding to the host)" that field, he represents the computer started the network services. Part of the IP description of the service is located on that interface, if the 127.0.0.1 is only for the local open, if 0.0.0.0 or:: The representative is open to the entire Internet. Each port has its own specific network service, and the relationship between several common ports and related network services is:
80:www
22:ssh
21:ftp
25:mail
111:RPC (Remote program Call)
631:cups (Print Service function)
Lychee 2) Suppose my host is interested in detecting the more common port 21, 22, 25 and 80 o'clock, how can I detect through netstat whether my host has the four main network service ports open? Since the keywords for each service are appended to the colon ":", they can be detected by retrieving a similar ": 80". Then I can simply write this program OH:
(29)
"Litchi" to write a script to run, let users enter his date of discharge, so you can help him calculate a few days before discharge.
Since the date is to be disposed of in a subtraction manner, we can use date to display the date and time, convert him to the number of seconds accumulated from 1970-01-01, after subtracting the number of seconds to obtain the remaining seconds, and then converted to the number of days. The entire script's production process is a bit like this:
1. First allow users to enter their date of discharge;
2. The date of discharge from the present date;
3. A comparison of two dates shows the words "it will take a few days" to be discharged.
It seems very difficult to look like. In fact, the use of "date--date=" YYYYMMDD "+%s" into seconds, the next move is much easier.
(30)
#!/bin/bash # Program: # with input your demobilization date, I calculate how to many days # before you demobilize
. # History: # 2005/08/29 Vbird-A-Path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin E Xport PATH # 1.
Inform the user of the purpose of the program, and tell them how to enter the date format. echo "This program would try to calculate:" echo "How many days before your demobilization date ..." read-p "please input Your demobilization date (YYYYMMDD ex>20090401): "Date2 # 2. Test to see if the input is correct. Use the formal expression of Faroese ~ date_d=$ (echo $date 2 |grep ' [0-9]\{8\} ') # to see if there are eight numbers if ["$date _d" = ""]; Then echo "You input the wrong date format ..." Exit 1 Fi # 3. Start calculation date rom ~ declare-i date_dem= ' Date--date= ' $date 2 ' +%s ' # Veterans date seconds declare-i date_now= ' Date +%s ' # now Number of seconds Declare-i date_total_s=$ (($date _dem-$date _now)) # Remaining seconds Statistics declare-i date_d=$ (($date _total_s/60/60/24)) # Convert to day I f ["$date _total_s"-lt "0"]; Then # judge whether the discharged echo "you had been DEmobilization before: "$ ( -1* $date _d)" "Ago" Else declare-i date_h=$ (($date _total_s-$date _d*60*60*24))/60/60 ) echo "You'll demobilize after $date _d and $date _h hours." Fi
(31)
"13.4.2" using CASE...ESAC to Judge
(32)
"Litchi" to modify the sh09.sh, as follows:
(33)
#!/bin/bash
# Program:
# show ' Hello ' from $ ... by using the case ... Esac
# History:
# 2005/08/29
vbird-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
Export The PATH case
is "hello")
echo "Hello, how are you?;
;
" "
echo "You must input parameters, ex> {$ someword}"
;
*) # In fact, is equivalent to the million bytes, 0~ infinite number of arbitrary byte meaning.
echo "Usage $ {Hello}"
;;
Esac
(34)
"Supplement" In general, the "$ variable" in the syntax of "case $ variable in" is generally used in two ways:
Direct release: As mentioned above, using the "script.sh variable" method to directly give the content of the variable, which is also in the/ETC/INIT.D directory most of the program design.
Interactive: Read this command to allow users to enter the contents of the variable.
"Litchi" allows users to enter one, two, three, and the user's variables are displayed on the screen, if not a, two, three, tell the user only these three choices. (through a direct execution to pass the parameter, that is, to give the contents of the variable directly by means of script.sh variable)
(35)
#!/bin/bash
# Program:
# This script is only accepts the flowing parameter:one, two or three.
# History:
# 2005/08/29 Vbird-A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin
export PATH
echo "This program'll print your selection!"
# read-p "Input Your choice:" Choice # is temporarily canceled and can be replaced.
# case $choice in # is temporarily canceled and can be replaced. Case
' in # is now used and can be replaced with two lines above.
"one")
echo "Your choice is one"
;;
" Two ")
echo" Your choice is two "
;;
Three ")
echo" Your choice is three "
;;
*)
echo "Usage $ {one|two|three}"
;;
Esac
"Continue Litchi"Allows the user to enter one, two, three, and displays the user's variable to the screen, and if it's not a, two, three, tell the user only these three choices. (reads the variable content entered by the user through the Read command)
(36)
"13.4.3" utilizes function functions
1 The syntax of the function is as follows:
function fname () {
Program Segment
}
That fname is our custom Run command name ~ and the program segment is what we want him to run. It is important to note that because the shell script is run from top to bottom, the function in the shell script must be configured at the top of the program to be able to find the available program segment at run time.
"Litchi" defines a function called PrintIt, as follows:
(37)
#!/bin/bash
# Program:
# Use function to repeat information.
# History:
# 2005/08/29 Vbird-A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin
export PATH
function PrintIt () {
echo-n "Your choice is" # Plus-n can continue to be displayed on the same line continuously c12/>}
echo "This program'll print your selection!"
case is in "one")
printit Echo | tr ' A-Z ' A-Z ' # converts the argument to uppercase or lowercase.
;;
" Two ")
PrintIt echo $ | tr ' A-Z '
;;
Three ")
PrintIt echo $ | tr ' A-Z '
;;
*)
echo "Usage $ {one|two|three}"
;;
Esac
2 In addition, the function also has built-in variables ~ His built-in variable is similar to shell script, the function name represents $, and subsequent variables are $ $ ... To replace the ~ it's easy to get it wrong. Because the $ $ in function fname () {program section}] And so on is different from the shell script's $ $. In the above sh12-2.sh, if I give: "Sh sh12-2.sh one", this means that in the shell script, the word "a" is the string. But the $ in printit () has nothing to do with this one.
"Litchi" will rewrite the above example again, as follows:
(38)
[Root@localhost scripts]# vim sh12-4.sh
#!/bin/bash
# Program:
# Use function to repeat information.
# History:
# 2005/08/29 Vbird-A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/ Usr/local/sbin:~/bin
export PATH
function PrintIt () {
echo "Your choice is $" this $ must refer to the order below c13/>}
echo "This program'll print your selection!"
Case "
One")
PrintIt 1 # Note that the PrintIt command also has a connection parameter behind it.
;;
" Two ")
PrintIt 2
;;
Three ")
PrintIt 3
;;
*)
echo "Usage $ {one|two|three}"
;;
Esac
"13.5" cycle
"13.5.1" while doing, until do (indefinite loop)
1) Circulation mode
Mode 1 while doing the loop: While Chinese is when .... , so this means that "when the condition condition is established, the circulation is carried out until the condition of the condition is not established to stop".
(39)
Mode 2) until do-done loop (indefinite loop): It says that when the condition condition is established, the loop is terminated, otherwise the program segment is continuously cycled.
(40)
"Litchi" while loop: let's say that I want the user to enter Yes or Yes to end the program, or keep telling the user to enter the string.
(41)
(42)
"Litchi" want to calculate 1+2+3+....+100 this data. Use the cycle AH.
(43)
"13.5.2" for...do...done (fixed cycle)
1 in relation to while, the until loop is a state that must "conform to a condition", for which the syntax is already known to take several loops. His grammar is:
(44)
2 Let us imagine another situation, because the system above the various accounts are written in the first field in the/etc/passwd, you can through the pipeline command cut to catch a simple account name, with ID and finger respectively check the user's identification code and special parameters.
(45)
"Supplement"
Supplemental 1 ID command: The ID command can display a truly valid user ID (UID) and group ID (GID). UID is a single identity for a user. The group ID (GID) corresponds to multiple UID.
Add 2 Finger command: The finger command is used to find and display user information. Both local and remote host users can be, the account name is not case-sensitive difference. Execute the finger instruction separately, it will show the local host now all the user login information, including account name, real name, login terminals, idle time, login time and address and phone.
(46)
"Litchi" Use ping this can judge the network status of the command, to carry out the actual network state detection, I want to detect the domain is the local 192.168.1.1~192.168.1.100, because there are 100 hosts, always do not want me to enter 1 to 100 for the back. You can do that right now. (But this machine only takes 10 machines.) )
(47)
#!/bin/bash
# program
# Use ping command to check the network ' s PC state.
# History
# 2009/02/18 vbird A-
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr /local/sbin:~/bin
export PATH
network= "192.168.1" first defines the front portion of a domain.
for Sitenu in $ (seq 1) # seq to sequence (continuous) acronym do
# The
program below gets the ping's return value to be correct or failed.
ping-c 1-w 1 ${network}.${sitenu} &>/dev/null && result=0 | | result=1
# starting to show that the result is correct start (up) or wrong Error not connected (down)
if ["$result" = 0]; then
echo "Server ${network}.${sitenu} is up."
else
echo "Server ${network}.${sitenu} is down."
Fi done
"Litchi"Write discriminant plus loop functionality: I want to let the user enter a directory file name, and then find the file name within a directory permissions, what to do.
(48)
(49)
numerical treatment of "13.5.3" For...do...done
1 for Loop there is another way of writing. The syntax is as follows:
(50)
2 This syntax is suitable for numerical methods of operation, in the parentheses after the three series of content meaning:
Initial value: The starting value of a variable in the loop, configured directly with a similar i=1;
Limit value: When the value of a variable is within the range of this limit, the loop continues. such as i<=100;
Run Step: The variable amount of variation for each time the loop is returned. For example