Learning Shell Scripts

2010-08-24  来源:本站原创  分类:OS  人气:199 

If you really want to go this route information, and you want Haohao De manage is your host, then do not tell your brother not to mention birds, Shell Scripts really need to study a subject too! Basically, shell script somewhat like the earlier batch file, which is compiled together some of the first implementation of the directive, but Shell script has a more powerful, that is, he can make a similar program (program) in writing, and do not need the compiled (compiler) to be able to perform, it is really easy. Plus, we can shell script to simplify the management of our daily work, and the entire Linux environment, a number of services (services) of the start is through shell script, if you do not understand the script, hehe! Problem occurs, there really could not get help Oh! So good, to learn a school him!

1. What is a Shell Script
1.1 Why learn shell scripts?
1.2 The first script of the writing and implementation of
1.3 Write a shell script to establish good habits
2. A simple shell script to practice:
3. Use of expressions:
3.1 Use the test function test instructions
3.2 Symbols used to judge []
3.3 Shell script for the default variable ($ 0, $ 1 ...)
4. Conditional:
4.1 use if .... then
4.2 Use case ..... esac judge
4.3 Use function function
5. Loop (loop)
5.1 while .... do .... done, until .... do .... done
5.2 for ... do ... done
6. Shell script to trace and debug
7. This chapter exercises to practice

-------------------------------------------------- ------------------------------
What is Shell scripts?

The interesting question to answer quickly see what is the shell script do? bash shell which we know has already been mentioned, it was under a text interface, so that we communicate with the system as a tool interface, then the script is what? Literally, script is 『script, the script』 meaning. The whole sentence is that, shell script is written for 『 shell script! 』 What ah? Ha ha! In fact, shell script is written using the functions of a shell 『 program (program) 』 , this procedure is to use text files, some of the syntax and command shell written in it, with a regular expression, re-pipe the command and data flow orientation and other functions, in order to achieve the purpose we want the treatment.

So, simply, shell script like the era of the early DOS batch file (. Bat), the simplest function is to compile a number of instructions to write together, so that the user is easily able to one touch (the implementation of a file "shell script", will be able to execute multiple instructions at once), but, shell script also offers an array, loop, conditional and logical judgments, and other important functions, so that users can write code directly to the shell without having to use a similar C programming language grammar written in the traditional program too!

That, so that you can understand it? Yes! The shell script can be as simple batch file, it can be said to be a programming language, and that this programming language Because they are using shell commands and tools, it can be executed without compilation, and has a good addition to error (debug) tool, so he can help system administrators manage a fast host.

-------------------------------------------------- ------------------------------
Why learn shell scripts?

This is a good question, why do I have to learn shell script? I'm not the information, and no written procedures for the concept, then why do I have to learn shell script do? Science Can not ah? Oh ~ If you run Linux, you just want 』『 will use it, then do not need to learn shell script is also also does not matter, this part of the give him jump over, wait until the free time, take a look again Haohao De . However, if you really want to play well the ins and outs of Linux, then the shell script will not know, why? Because:

An important basis for automated management:
Brother Bird says you do not know, manage a host really is not an easy thing, every day tasks to be carried out there: check log files, tracking traffic, monitoring the user using the host state, host state of the hardware device, the host software update check, not to speak to cope with the sudden demands of other users. These work, you want to deal with their own hand, or write a simple program to help you automate a daily analysis of the problem if only to inform you? Of course, the system automatically work better, right! Oh ~ This may be a good shell script to help your friends!

Tracking and management systems important work:
Although we have not mentioned the method of service start, but I'll let you mention, our Linux system services (services) start interface, in / etc / init.d / to this directory, all files are scripts; In addition, including the boot (booting) process are also using shell script to help search for data related to the system settings, and then substituted into the set parameters of each service ah! For example, if we want to restart the system log files, you can use: 『/ etc / init.d / syslogd restart』 , that syslogd is the script file it! Also, I had found a generation of FC above, start the MySQL database service, this is indeed a start, but it always appears on the screen 』『 failure, and later discovered that the original is to start MySQL script that will take the initiative in order to 『 try empty password to log in MySQL, but I changed the password for MySQL login failure Hello ~ ~ Later, of course, changed changed script, omitted the question on it! Having said that, script really needs to learn, ah!

Simple intrusion detection features:
When our system is abnormal, the most records in the system will record these abnormal device, which is often referred to in our log files 』『 system, then we can take the initiative in fixed within a few minutes to analyze the system registry files of If aware of the problem, inform the administrator immediately, or immediately strengthen the firewall rule set, this way, your host may be able to protect themselves 』『 smart learning function Rights ~ For example, we can shell script to analyze 『When the packet or on-line after the failure of several attempts, the IP』 to withstand the sort of move, for example, wrote a Colombian birds to resist the cutting station on the software shell script, was reached with the idea to too!

One of continuous instruction:
In fact, for starters, script is the most simple function: 『 compile some command line instructions issued by the continuous, which he writes scripts, but by the direct implementation of the scripts to start a series of command line command O! 』 For example: firewall rules row (iptables), the boot loader project (that is in the / etc / rc.d / rc.local inside the data), and so are all the same functions it! In fact, put it bluntly, if you do not take into account the part program, then the scripts can think of, just a long list of instructions to help us to compile a file inside, and direct the implementation of the file that can be performed and long string of smelly The instruction section! Is as simple as it!

Simple data processing:
From the previous chapter, the awk regular expression description of the procedures, you can see, awk can be used to handle simple data data too! For example, payroll processing, etc. ah. more powerful shell script, for example, Colombia had a bird with a shell script to process data directly comparing ah data, text, data processing, etc. ah, writing convenience, speed and fast (because of better performance in Linux), really very good use of it!

Cross-platform support and a shorter learning process:
Almost all Unix Like the above can run shell script, even the MS Windows family also can be related to the simulator, in addition, shell script syntax is very amiable and see all the know how to read the text, rather than machine code, it is easy You can learn ~ These are the learning points to be considered ah!

These are the top shell script you are considering learning the characteristics of ~ In addition, shell script to vi can also be simple to write directly, it is very convenient for the good stuff! Therefore, it is recommended that you learn about friends.

However, although the shell script is a program called (program), but in fact, shell script data processing speed is not enough. Because the shell script using a bash shell external commands and some of the default tools, so he often would go to call an external library, so of course the above computation speed as the more traditional programming language. So, La, shell script used in the systems management tools for the above is a good one, but with a large number of numerical computation in the processing, it is not good enough a ~ and very troublesome, because: Shell scripts slower, and the use of the CPU more resources, resulting in poor allocation of host resources. Fortunately, we do very little shell script that use large amounts of data during operation, so do not worry about it!

-------------------------------------------------- ------------------------------
The first script of the writing and implementation of

As mentioned earlier, shell script is in fact text files (ASCII), we can edit the file, and then let this file to help us once more than one instruction, or the number of operations and logic used to help us reach some of the judge function. So the matter, to edit the contents of this file, of course, need to have a bash shell commands issued by the relevant knowledge. We have said that needs to be directed attention at the bash chapters already mentioned, in the shell script used to write the same need to pay attention to these matters:
As mentioned earlier bash command, instruction and a number of parameters blank will be ignored;
The blank lines will be ignored! And [tab] it will not be ignored in!
If you read a Enter symbol (CR)), to try to start the implementation of the command line;
As if the line is too big, you can use \ [Enter] to extend to the next line;
In addition, the use of most of # can be used as comments! Any increase in the # behind the words, will all be considered as text and comments are ignored!
Thus, we have the procedures written within the script, will be the implementation line by line. Well, then, assuming the program file name is shell.sh Well, how to implement this file? Very simple, can have several methods below:
And implementation will shell.sh with readable (rx) permissions, and then be able to. / Shell.sh to perform a;
Direct way to sh shell.sh can be directly executed.
Anyway point is to let the shell.sh instructions can be executed within the meaning of it! Hey! That why I need to use. / Shell.sh to give instructions? Recall that when we bash which has been stressed, whether an instruction can be performed with the PATH environment variable to this, so, to perform 『current directory will need to add a file』 . / This directory it! In addition, the fact you can also shell.sh on your home directory ~ / bin this directory, and then use PATH = "$ PATH": ~ / bin set, hey, will be able to run your script directly to La ~ ^ _ ^

Well, why sh shell.sh can also be enforced? This is because / bin / sh is actually / bin / bash, which tell the system to use sh shell.sh, I want to bash the function directly to the Executive shell.sh this file within the meaning of the relevant directives. We can also use sh parameters, such as-n and-x to check the syntax and tracking shell.sh correct it! ^ _ ^

-------------------------------------------------- ------------------------------

Write the first script
Whether the martial art to learn martial arts from the start sweeping, then to learn procedures? Oh, certainly showed off by 『 Hello World! 』 Word started! OK! Then the birds start to write a script to Columbia for everyone to take a look:
[Root @ linux ~] # mkdir scripts; cd scripts
[Root @ linux scripts] # vi sh01.sh
#! / Bin / bash
# Program:
# This program is used to show "Hello World!" In screen.
# History:
# 2005/08/23 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH
echo-e "Hello World! \ a \ n"
exit 0

In this chapter we were, please place all of the writing of the script to your home directory ~ / scripts in this directory, better management of it! Written above them, I mainly write the entire program is divided into sections, roughly like this:
The first line #! / Bin / bash declare this in shell script using the name:
Because we are using bash, it must be to 『 #! / Bin / bash to come to declare the syntax of this file using bash syntax! Then when the program is executed, he will be able to load the bash configuration files related to the environment, and implementation of the bash to make our instructions below to perform! This is very important! (In many situations, if the line is not configured, then the program will likely not be implemented because the system could not determine what the program needs to use the shell to perform ah!)

Program content of the declaration:
The entire script, not only the first line #! Is used to declare the outside shell, the other # were all endorsed 』 use! Therefore, among the above procedure, the second line of the following is used to describe the state of the whole process. Generally, we recommend that you have to develop a description of the script: 1. The content and functionality; 2. Version information; 3. Author and contact details; 4. Filing date; 5. The historical record and so on. This will help rewrite the future of the program and debug it!

Major environmental variables declared:
Proposal must be to set some important environment variables is good, birds Colombian think, PATH is the most important! This way, you can let our police procedures in progress, can be directly issued orders, without having to write the absolute path to it! Comparison of right!

Some of the main program will be the main program can be written! In this example, the line is the echo it!

Implementation of the results of this remember that we bash command inside to discuss the implementation of a success, you can use $? This variable to observe ~ then we can also use this command to exit the program to interrupt, and return a value to the system. In our example, when I use the exit 0, this means leave the script, and return a 0 to the system, so I finished the script after execution, if ordered then echo $? Can get the value 0 Oh! More intelligent readers should also know, huh, huh! Use this exit n functions, we can customize the error message, so Zhezhi procedures become more the smart too!
The next execution to see what was the result, right?
[Root @ linux scripts] # sh sh01.sh
Hello World!

You will see the screen is so, and should also hear 』『 boom crash, why? Printf remember it mentioned in the previous chapter? Then use echo those special touches that can happen the same thing ~ But, echo-e must be added the parameters Caixing! Ha ha! When you finish this little script, you can say it: I would have written procedures for the 『』 ! Haha! Very easy and fun it ~ ^ _ ^

In addition, you can use: 『 chmod a + x sh01.sh; ./sh01.sh 』 to execute this script too!

-------------------------------------------------- ------------------------------
Write a shell script to establish good habits

A good habit is very important ~ we at the beginning of written procedures, the most easy to overlook this part of the program written like that, and the other is not important. In fact, if the description of the procedures more clearly, then on your own is a great help.

For example, birds to their needs his brother, who has written a lot of script to help me to host IP detection, ah, ah log file analysis and management, automatic upload to download configuration files ah and so important, However, early because too lazy, and the management of the host it too much, often with a different host in the above program changes, and finally, in the end which one is the latest of all do not remember, but the focus is Where I am in the end is changed? ? Why do that kind of changes? Forget the pretexts are really terrible ~ ~

So, then birds and Colombia, written procedures, usually more careful of the design process to his record, but also recorded a number of historical record, this way, much better ~ at least it is easy to know what data I modified and the application to modify the concept of ideas and logic and so on, in the maintenance of the above is a lot easier a lot of Oh!

In addition, some environmental settings above, after all, everyone's environment is different, in order to achieve a better implementation of the environment, I would be better to define their own will be used environment variables, such as PATH this stuff! This is more so bad ~ So, we recommend that you have to develop good writing habits script, each script file in the record of the first good:
script functions;
script version of the information;
script of the author and contact details;
script copyright declaration form;
script of History (history);
script of the more specific instructions, use absolute path ordered way;
script when the operation of pre-announcement of the environment variables and settings.

-------------------------------------------------- ------------------------------
Simple shell script exercise

In the first shell script has finished writing, I believe you should have a basic writing skill. Next, at the beginning of the procedure in greater depth the concept, we first play some of the more interesting examples of simple little better. Example below, the settled and require considerable of the many suggestions you first write their own look and birds after finishing to write the content than Colombian right, it can be deepened Gainian Oh! Good! Not verbose, we one by one to play with me!

-------------------------------------------------- ------------------------------

Variable content of the decision by the user are often some of the elements we need to user input, so that programs can operate smoothly. Simple terms, we should have the experience of the software installed, the installation, he will not ask you to install to that directory 『go? 』 It? That allows users to input data action, which is the content of Rights allow users to input variables.

You should also remember that in the bash, we have learned a read command, right? Forget it, please go back to read something on their own. Now, please read instructions to use, write a script, he can allow users to enter: 1 first name and 2. Last name, last and displayed on the screen: 『 Your full name is: 』 content:
[Root @ linux scripts] # vi sh02.sh
#! / Bin / bash
# Program:
# Let user keyin their first and last name, and show their full name.
# History:
# 2005/08/23 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

read-p "Please input your first name:" firstname
read-p "Please input your last name:" lastname
echo-e "\ nYour full name is: $ firstname $ lastname"

The implementation of the above this sh02.sh look, you can find the user input their own variables that can be drawn in the battle! Very good it! Come on!

-------------------------------------------------- ------------------------------

Use the file date for the establishment of
Imagine a situation, if I back up every day, but do not want to back up data to be overwritten, that is, I want to back up data every day on a different file. Wow! This really troubled ah? Do you want me to modify every script? Need ah! 』『 Date because not every day the same, so I can get into a similar file name: backup.20050802, not to a different file name each day yet? Ha ha! Indeed. Well, then the example: I want to create three empty files, file name input by the user decide the most at the beginning, assuming that the user enter the filename right, then today's date is 2005/08/23, and I would like to to previous day, yesterday, today's date to create this file, which filename_20050821, filename_20050822, filename_20050823, what to do?
[Root @ linux scripts] # vi sh03.sh
#! / Bin / bash
# Program:
# User can keyin filename to touch 3 new files.
# History:
# 2005/08/23 VBird First release
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 get fileuser this variable;
echo-e "I will use 'touch' command to create 3 files."
read-p "Please input the filename what you want:" fileuser

# 2. In order to prevent users from freely by Enter, the file name by using the variable function of whether the set?
filename = $ (fileuser: - "filename")

# 3. Started to use date command to get the required file name of the;
date1 = `date - date = '2 days ago '+% Y% m% d`
date2 = `date - date = '1 days ago '+% Y% m% d`
date3 = `date +% Y% m% d`
file1 = "$ filename" "$ date1"
file2 = "$ filename" "$ date2"
file3 = "$ filename" "$ date3"

# 4. The file name to establish it!
touch $ file1
touch $ file2
touch $ file3

I through some simple movements, these movements can be found in the bash inside the chapter, including small command (`) to acquire information, the variable setting functions, variables and the use of touch commands cumulative aid! If you started this sh03.sh, you can enter twice, once directly by the [Enter] to inspect the file name is what? One can enter some characters, so your files to determine Oh! Instructions on the date of application, please man date it! ^ _ ^

-------------------------------------------------- ------------------------------

Tell me what you value calculation method should also remember that we can use to define variables declare the type, right? ! Only in this way to carry out addition and subtraction ah! Unfortunately, bash shell inside the default only supports the integer data. OK! Then we come to play it, if we want users to enter two variables and then multiplying the contents of two variables, the final output multiplied results, it can how?
[Root @ linux scripts] # vi sh04.sh
#! / Bin / bash
# Program:
# User can input 2 integer to cross by!
# History:
# 2005/08/23 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH
echo-e "You SHOULD input 2 number, I will cross they! \ n"
read-p "first number:" firstnu
read-p "second number:" secnu
total =$(($ firstnu * $ secnu))
echo-e "\ nThe number $ firstnu x $ secnu is ==> $ total"

In digital computing, we can use 『 declare-i total = $ firstnu * $ secnu 』 can also use the above method to be! Basically, the birds more recommended Costa Rica to conduct operations in such a way:
var = $ ((computing elements))
Not only easy to remember, but also more convenient and more ~ the future you can use this method to calculate the Yeah! As for the handling of numerical computation, there are: +, -, *, /,% and so on. That% is to take the remainder ! ~, for example, 13 to 3 to take the remainder, the result is 13 = 4 * 3 +1, so the remainder is 1 ah! Is:
[Root @ linux scripts] # nu = $ ((13% 3)); echo $ nu
1

This understanding of it? ! To learn and apply Oh! ^ _ ^

-------------------------------------------------- ------------------------------
Use of predicate

In the bash section, we mentioned $? Significance of this variable represents, in addition, also through the & & and | | used as a command before it can be successful as a reference. So, if I want to know / dmtsai when this directory exists, does it have to use ls to do, and then to $? To determine the implementation of the outcome of it? Ha ha! Certainly do not need! Through the test we turning this command to detect it!

-------------------------------------------------- ------------------------------
Using the test function test instructions

When I want to test the system above is related to certain files or property, use this command to work test is really incredibly easy to use, for example, I want to check / dmtsai the existence, use:
[Root @ linux ~] # test-e / dmtsai

Implementation of the results will not display any messages, but in the end we can $? Or & & and | | to show the results too! For example, we rewrite in the example above like this:
[Root @ linux ~] # test-e / dmtsai & & echo "exist" | | echo "Not exist"

The end result can tell us exist 』『 』 or 『 Not exist too! That I know-e was tested in the absence of a 『』 thing, if you have the file name you want to test the hell is a child, what are the signs can come to judge it? Ha ha! Oh these things are below!

The symbol represents the significance test
1. On a file name 』『 type detection (presence or not), such as test-e filename
-E The file name 』『 existence? (Common)
-F the file name 』『 whether the file (file)? (Common)
-D the file name 』『 whether the directory (directory)? (Common)
-B The file name 』『 whether a block device device?
-C The file name 』『 whether a character device device?
-S the file name 』『 whether a Socket file?
-P The file name 』『 whether a FIFO (pipe) file?
-L of the file name 』『 whether a link file?
2. Permissions on files to detect, such as test-r filename
-R detect whether the file name attribute 』『 readable?
-W to detect whether the file name can be written 』『 property?
-X detects whether the file name of the executable 』『 property?
-U to detect whether the file name 』『 SUID attribute?
-G detect whether the file name 』『 SGID attributes?
-K to detect whether the file name attribute 』『 Sticky bit?
-S to detect whether the file name 』『 non-empty file?
3. Comparison between two files, such as: test file1-nt file2
-Nt (newer than) to judge whether the more than file2 file1 new
-Ot (older than) to judge whether file1 older than file2
-Ef file2 and file2 to judge whether the same file, can be used in judging the judge on the hard link. Major significance in determining, whether two files are pointing to the same inode miles!
4. On the determination between the two integers, such as test n1-eq n2
-Eq values equal to two (equal)
-Ne 2 values ranging from (not equal)
-Gt n1 is greater than n2 (greater than)
-Lt n1 is less than n2 (less than)
-Ge n1 is greater than equal to n2 (greater than or equal)
-Le n1 is less than equal to n2 (less than or equal)
5. Determine the string of data
test-z string string is determined to 0? If the string is an empty string, was true
test-n string string to determine whether the non-0? If the string is an empty string, was false.
Note:-n can be omitted
test str1 = str2 str1 determine whether the mean str2, if equal, return true
test str1! = str2 determine whether str1 is not equal to str2, if equal, return false
6. Multiple terms of determining, for example: test-r filename-a-x filename
-A (and) the two conditions set up for! For example, test-r file-a-x file, the file also has r and x permission only return true.
-O (or) any one of the two conditions set up! For example, test-r file-o-x file, the file permissions with r or x, you can return true.
! RP state, such as the test!-X file, when the file does not have x, return true

OK! Now that we have used the test to help us write a few simple examples. First, determine what, let the user enter a file name, we determine:
This file exists, if there is given a 』『 Filename does not exist message, and interrupt procedures;
If this file exists, the judge he was a file or directory, the resulting output 』『 Filename is regular file or 』『 Filename is directory
Judge if the implementation of the identity of this file or directory that has permissions, and data output permission!
You can first create their own look, and then talk to the result of discussions under discussion. Note also the use test and & & | | and other signs!
[Root @ linux scripts] # vi sh05.sh
#! / Bin / bash
# Program:
# Let user input a filename, the program will search the filename
# 1.) Exist? 2.) File / directory? 3.) File permissions
# History:
# 2005/08/25 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

# 1. Let the user enter a file name, and determine whether users really have input string?
echo-e "The program will show you that filename is exist which input by you. \ n \ n"
read-p "Input a filename:" filename
test-z $ filename & & echo "You MUST input a filename." & & exit 0
# 2. Determine whether a file exists?
test!-e $ filename & & echo "The filename $ filename DO NOT exist" & & exit 0
# 3. Start determining file type 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 & & perm = "$ perm executable"
# 4. Start output!
echo "The filename: $ filename is a $ filetype"
echo "And the permission are: $ perm"

Very interesting example of it! You can customize the case then other features available to write about it!

-------------------------------------------------- ------------------------------
Symbols used to judge []

In addition we like to use the test, is in fact, we can determine symbol 『 [] data of the judge to come to it! For example, if I want to know whether $ HOME This variable is empty, you can do:
[Root @ linux ~] # [-z "$ HOME"]

But using [] It should be noted that, in the middle of each component needs to have separated the space bar, assuming I use the space bar □ 』『 represented, then, in these places you need to have space Key:
["$ HOME" == "$ MAIL"]
[ □ "$ HOME" □ == □ "$ MAIL" □ ]
↑ ↑ ↑ ↑

The above examples show that the two strings with the $ MAIL $ HOME is the same means, the equivalent test $ HOME = $ MAIL mean it! If not separated by spaces, such as [$ HOME == $ MAIL], our bash will display an error message was! This will happen very careful ah! So, you better pay attention to:
In brackets [] are required for each component space bar to separate;
Variable in brackets, preferably all double quotation marks to set;
Constant in the brackets, the best single or double quotation marks are set.
For example, if I set the name = "VBird Tsai", then this determination:
[Root @ linux ~] # name = "VBird Tsai"
[Root @ linux ~] # [$ name == "VBird"]
bash: [: too many arguments

Why? For $ name if not using double quotes bitch to, then determine the type above would become:
[VBird Tsai == "VBird"]
Not what we want:
["VBird Tsai" == "VBird"]
This is bad, but a lot of Oh! In addition, the use of parentheses and the test is almost identical with the sign ah ~ is more common in parentheses in the conditional if ..... then ..... fi situations it wants. Well, that we continue to do a little case of Well:
When the execution time of a program, this program will let users choose Y or N,
If the user enters Y or y, to show 『OK, continue』
If the user enters n or N, on display 『 Oh, interrupt! 』
If not, Y / y / N / n of the other characters on the show 『 I don't know what is your choise 』
The use of brackets, & & and | | to continue it!
[Root @ linux scripts] # vi sh06.sh
#! / Bin / bash
# Program:
# This program will show the user's choice
# History:
# 2005/08/25 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

read-p "Please input (Y / N):" yn
["$ Yn" == "Y"-o "$ yn" == "y"] & & echo "OK, continue" & & exit 0
["$ Yn" == "N"-o "$ yn" == "n"] & & echo "Oh, interrupt!" & & Exit 0
echo "I don't know what is your choise" & & exit 0

Very interesting now! Identification method using the string, we can very easily be the work of different categories the user wants to do! Next, let's talk about some other things, some do not it!

Tips:
Why judge issued a type which is equal to use == instead of a = like out? Regular expression in the previous chapter inside awk mentioned, only one = used to set the contents of a variable, the logical judgments, will be given two equal, which is set 『』 『 more 』 not mean ~ here are to upgrade resolved look Oh! ^ _ ^

-------------------------------------------------- ------------------------------
Shell script for the default variable ($ 0, $ 1 ...)

In fact, when we execute a shell script, the shell script in which this had to help us do some of the available variables. For example, in the near future, you will find, when we want to start a system service may be issued instructions like this:
[Root @ linux ~] # / etc / init.d / crond restart

It is valid and stuff? Ha ha! People I say to the / etc / init.d / crond restart this script instructions issued 』 , Hey! We do not use read to read user input variable content? Why I can connect directly to the back of this parameter in the script? This is because the shell script to help us better specify the variables to set up! Corresponding variables like this:

/ Path / to / scriptname opt1 opt2 opt3 opt4 ...
$ 0 $ 1 $ 2 $ 3 $ 4 ...

This clear enough, right? ! Implementation of the file name is $ 0 to this variable, the first parameter is $ 1 then ah ~ So, if we use $ 1 in the script which then can be immediately issued some very simple instructions feature it! Well, to make a case it ~ If I want to execute a script, executed, the script will automatically display their file name, there followed by his first three parameters, what to do?
[Root @ linux scripts] # vi sh07.sh
#! / Bin / bash
# Program:
# The program will show it's name and first 3 parameters.
# History:
# 2005/08/25 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

echo "The script naem is ==> $ 0"
[-N "$ 1"] & & echo "The 1st paramter is ==> $ 1" | | exit 0
[-N "$ 2"] & & echo "The 2nd paramter is ==> $ 2" | | exit 0
[-N "$ 3"] & & echo "The 3th paramter is ==> $ 3" | | exit 0

Zhe Zhi Ge Jia program on a number of birds inside the control type, which use & & and | | to be judged by $ 1 to $ 3 exist? If there is only shown if there is to break ~ the implementation of results are as follows:
[Root @ linux scripts] # sh sh07.sh theone haha quot
The script naem is ==> sh07.sh
The 1st paramter is ==> theone
The 2nd paramter is ==> haha
The 3th paramter is ==> quot

The seven examples above are simple, right? Almost all of the relevant functions using bash it is not difficult to ! ~ ~ under the conditional we have to use to carry out some functions of the set, respectively, well take a look first ~

-------------------------------------------------- ------------------------------
Conditional:

Just have to mention 『Procedures, then the conditional, that is, if then』 『 sure this discriminant must learn! Very often, we all have to be based on some of the data to determine how to program. For example, we have to practice when not on top of the user input Y / N, the need to implement different message output? Simple ways to use & & and | |, but if I want to run a bunch of commands do? If then it really got to the bottom to help Hello ~ We have to chat!

-------------------------------------------------- ------------------------------
Use if .... then

If .... then this is the most common conditional statement of the ~ simply, is that when a conditional line when it wants to be in a job. We can simply this way:
if [conditional]; then
When the conditional set up, the instruction can work content;
fi

The conditional judgment methods, and the introduction of the previous section the same as ah! More special is that, if I have multiple factors that must determine when, Chu Le sh06.sh that case, wherein a number of conditions to write the bracketed the real situation, I can have multiple brackets Huan Lai separated Oh! Between the brackets and parentheses, Zeyi & & or | | to separate, their meaning is:
& & For AND;
| | On behalf of or;
Therefore, the use of brackets in the type of judge, & & and | | with the instructions issued on the status of different. For example, sh06.sh examples that I can rewrite like this:
[Root @ linux scripts] # vi sh06-2.sh
#! / Bin / bash
# Program:
# This program will show the user's choice
# History:
# 2005/08/25 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

read-p "Please input (Y / N):" yn

if ["$ yn" == "Y"] | | ["$ yn" == "y"]; then
echo "OK, continue"
exit 0
fi
if ["$ yn" == "N"] | | ["$ yn" == "n"]; then
echo "Oh, interrupt!"
exit 0
fi
echo "I don't know what is your choise" & & exit 0

However, by the looks of this case, it seems not so great, right? sh06.sh it ~ but still relatively simple, if we consider the bottom of the state, if then you will know the benefits:
if [conditional]; then
When the conditional set up, the instruction can work content;
else
When the conditional is not established, the instruction can work content;
fi

If we consider more complex situations, you can use this syntax:
if [conditional 1]; then
When the conditional expression of a set, you can carry out the instructions on the content;
elif [conditional 2]; then
When the conditional two established, can the content of the instruction work;
else
When the conditional 1 and 2 are not established, the instruction can work content;
fi

Then I can sh06-2.sh changed to this:
[Root @ linux scripts] # vi sh06-3.sh
#! / Bin / bash
# Program:
# This program will show the user's choice
# History:
# 2005/08/25 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

read-p "Please input (Y / N):" yn

if ["$ yn" == "Y"] | | ["$ yn" == "y"]; then
echo "OK, continue"
elif ["$ yn" == "N"] | | ["$ yn" == "n"]; then
echo "Oh, interrupt!"
else
echo "I don't know what is your choise"
fi

Whether the procedure becomes very simple, and order of judging, can avoid repeating the situation to judge, so really easy to design the program it! ^ _ ^ Well, then, if I want to detect whether the parameters you have entered it for the hello, that is, if I want to know, then you are in the process behind the first parameter (that is $ 1 ah!) Whether hello,
If so, this will show "Hello, how are you?";
Without any arguments, it prompts the user must be assigned to the parameters used method;
If adding the parameter is not hello, hello to remind users to only use the parameter.
The entire procedure can be written like this:
[Root @ linux scripts] # vi sh08.sh
#! / Bin / bash
# Program:
# Show "Hello" from $ 1 ....
# History:
# 2005/08/28 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

if ["$ 1" == "hello"]; then
echo "Hello, how are you?"
elif ["$ 1" == ""]; then
echo "You MUST input parameters, ex> $ 0 someword"
else
echo "The only parameter is 'hello'"
fi

Then you can do Zhezhi steps in the $ 1 position input hello, there is no input and random input, you can see the different output Hello ~ it is also like a simple, ah! ^ _ ^. In fact, the learned here, it is amazing the ~ Well, we continue to play under some of the more bigger Hello ~ We have learned in the previous chapter grep this nice stuff, so many school called netstat command, this command can query the current host has to open the network service port port (service ports), related functions will continue to introduce articles in the server set up, where you just know that I can fully make use of netstat-tuln to come to get the current host has started the service, and information obtained something like this:
[Root @ linux ~] # netstat-tuln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:199 0.0.0.0: * LISTEN
tcp 0 0::: 80::: * LISTEN
tcp 0 0::: 22::: * LISTEN
tcp 0 0::: 25::: * LISTEN

The focus above is that part of the special fonts, special fonts that some representatives of port Hello ~ it is the meaning of each port to? Several common network services and related port relationship is:
80: WWW
22: ssh
21: ftp
25: mail
What can I do through my netstat to detect whether the host opened the four major network service port mouth? I can simply write the program this way Oh:
[Root @ linux scripts] # vi sh09.sh
#! / Bin / bash
# Program:
# Using netstat and grep to detect WWW, SSH, FTP and Mail services.
# History:
# 2005/08/28 VBird First release
PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
export PATH

# 1. First make some informed of the action only ~
echo "Now, the services of your Linux system will be detect!"
echo-e "The www, ftp, ssh, and mail will be detect! \ n"

# 2. To begin the work of some tests, and also some information on the output Hello!
testing = `netstat-tuln | grep": 80 "`
if ["$ testing"! = ""]; then
echo "WWW is running in your system."
fi
testing = `netstat-tuln | grep": 22 "`
if ["$ testing"! = ""]; then
echo "SSH is running in your system."
fi
testing = `netstat-tuln | grep": 21 "`
if ["$ testing"! = ""]; then
echo "FTP is running in your system."
fi
testing = `netstat-tuln | grep": 25 "`
if ["$ testing"! = ""]; then
echo "Mail is running in your system."
fi

This way, we can check one by one is very interesting La ~ ah! ^ _ ^. Next, let us play a little more difficult. We know that can use the date to display the date and time, you can use $ ((Formula)) to calculate the numerical computation. In addition, date can also be used to display from the 19,710,101 total number of seconds since 『』 (Please access man date and info date). So, you can write a small program used to calculate ex 『

相关文章
  • Learning Shell Scripts 2010-08-24

    If you really want to go this route information, and you want Haohao De manage is your host, then do not tell your brother not to mention birds, Shell Scripts really need to study a subject too! Basically, shell script somewhat like the earlier batch

  • Learning Shell Scripts (2) 2010-08-24

    『Calculated for a few days left on ex-date? 』 In other words: let users enter their ex-date; then ex-date than the date now; by the comparison of two dates to show a few days 』 『 also need to be able to discharge the words. Is very hard to seem like?

  • Bash shell scripts to use functional testing 2010-06-17

    Functional testing is a key part of software development - and have loaded Linux, Bash can help you easily complete the functional tests. In this article, Angel Rivera will explain how to use the Bash shell script to run through the Linux command lin

  • shell scripts: one to read the file line 2010-03-18

    Reprinted shell scripts: one to read the file line, and the output written a collection: #! / Bin / bash while read line do echo $ line # here may change based on actual use done <urfile Written b: #! / Bin / bash cat urfile | while read line do echo

  • Create and run shell scripts 2010-05-12

    shell script that contains one or more command files. shell script provides a lengthy command execution, large or complex command sequences, and routine tasks simple way. When you enter the name of shell script file, the system will execute the file

  • 10 Tools To Add Some Spice To Your UNIX Shell Scripts 2010-08-17

    T here are some misconceptions that shell scripts are only for a CLI environment. You can easily use various tools to write GUI and / or network (socket) scripts under KDE or Gnome desktops. Shell scripts can make use of some of the GUI widget ( menu

  • Top DBA Shell Scripts for Monitoring the Database 2010-08-19

    Basic UNIX Command The following is a list of commonly used Unix command: + ps - Show process + grep - Search files for text patterns + mailx - Read or send mail + cat - Join files or display them + cut - Select columns for display + awk - Pattern-ma

  • Exercise 2 shell scripts 2010-09-07

    Exercise 2 shell scripts

  • Shell scripts for encryption 2010-11-07

    Shell scripts for encryption shc encrypted shell script is a tool. It is the role of the shell script into an executable binary file. Using shell scripts to automate system maintenance, simple, convenient and good portability. But the shell script is

  • Linux system shell scripts to determine the variable file directory: permission. Exists. Empty. Equal 2011-05-06

    Linux system shell scripts to determine the variable file directory: permission exists, null value, equal The first to write some of the basic syntax: 1, the string to determine str1 = str2 When two strings have the same content, the length of time i

  • Bukanhouhui Shell scripts for Linux production servers to share 2011-03-06

    Bukanhouhui Shell scripts for Linux production server share as a Linux / unix system administrator, I often encounter people ask this question: shell do? PHP so powerful, why not use PHP to complete the work? In fact, relative to the PHP development

  • Linux system shell scripts to determine the variable file directory: permissions exist. Null. Equal 2011-05-06

    Linux system shell scripts to determine the variable file directory: permission exists, null value, equal First write the basic syntax: 1, the string to determine the str1 = str2 When two strings have the same content, the length of time is true str1

  • A comprehensive study of Linux shell scripts 2010-11-04

    Transfer source: Linux commune Author: Linux http://www.linuxidc.com/Linux/2007-06/4767.htm 1. Linux-based scripting Introduction 1.1 Basic syntax 1.1.1 at the beginning Program must begin with the following line (be the first line in the file side):

  • linux systems using shell scripts to create FTP account 2010-03-09

    Following SHELL script to create a more complete FTP account, including: 1) The new FTP account and directory 2) FTP account password changes 3) FTP account directory, create three subdirectories, different data storage 4) The directory permissions s

  • Practical cfg file to modify shell scripts ------- 2010-10-27

    1. Cfg file used to modify the shell script: #! / Usr / bin / ksh function cfg_update_sec_key_value { typeset file_name = "$ 1" typeset sec_name = "$ 2" typeset key_name = "$ 3" shift 3 typeset key_value set-A key_value "

  • informatica workflow call shell scripts and return to the state parameter processing 2010-11-01

    informatica, with a shell script calls the workflow, as long as the next path to be able to use it! Posted out to you the essence of part of the share #!/bin/sh cd /oracle/app/infa/Server/server/bin if [ -f /backup/data/zktest/SES_MAP_IRS_DATA_REVISE

  • Example shell scripts Summary 2010-11-07

    Jack and tom ------------------- requirements calculated the average of 2 families with a shell implementation. cat 1.txt jack huaxue 90 tom huaxue 70 jack shuxue 99 tom shuxue 80 awk well to achieve awk '{a [$ 1] + = $ 3} END {for (i in a) print i,

  • duplication and a few shell scripts to note 2011-01-31

    1. Spread the linux machine with SSH shell script, you need to use vim dos.txt :set fileformat=unix :w Conversion, otherwise there may be syntax error: unexpected end of file exception. 2. If you want to re-file text processing, raw data: a 1 1 1 b 2

  • Commonly used in shell scripts 2011-03-09

    1, parameters are passed between the script "1.sh" script to accept arguments. As if there is a parameter of this variable is assigned a sourceFile, or use the default values. #!/bin/bash LANG=en_US.UTF-8 #get parameters sourceFile="/data/l

  • informatica workflow call shell scripts and returns processing status parameters 2010-11-01

    informatica, with a shell script called workflow, as long as the next path will be able to use it! The best parts posted for everyone to share, #!/bin/sh cd /oracle/app/infa/Server/server/bin if [ -f /backup/data/zktest/SES_MAP_IRS_DATA_REVISE_RECORD