Shell programming

Source: Internet
Author: User

Tags: win multiple definition share Picture command indicates sed understanding match

1, write a simple script

Shell Terminal interpreter can be used as a "translator" between human and computer hardware, as a communication medium within the user and Linux system, in addition to supporting a variety of variables and parameters, but also provides such as loops, branches and other advanced programming language has the control structure characteristics.

For example, if you want to see the current working path and list all the file and attribute information in the current directory, the script that implements this function should look like this:

[email protected] desktop]# Vim a.sh #!/bin/Bash
-/root/41 Sep 8: a.sh

The name of the shell script file can be arbitrary, but in order to avoid being mistaken for an ordinary file, it is recommended to add the. sh suffix to indicate that it is a script file.

There are actually three different elements: the first line of the script declaration (#!) tells the system which shell interpreter to use to execute the script, and the second line of comment information (#) is a description of the script feature and some commands that allow yourself or others to see the script content later on. You can quickly know what the script does or some warning messages, and the executable statement on line third to fourth is the Linux command we normally execute.

2, the parameters of the receiving user

Such a script can only perform some pre-defined functions, it is too inflexible. In order for the shell script to better meet some of the real-time needs of the user in order to work flexibly, it is necessary for the script to receive the user input parameters as it did before the command was executed.

For example

$ A corresponds to the name of the current shell script program

$ #对应的是总共有几个参数,

The $* corresponds to the parameter values for all positions,

$? Corresponds to the display of the execution return value of the last command,

and $, $, $ ... corresponding to the nth position parameter values, respectively.

[email protected] desktop]# Vim a.sh #!/bin/Bashecho"the current script name is $"Echo"There are a total of $ #个参数, respectively, $*. "Echo"The 1th parameter is $ $, and the 3rd is $ A. "[email protected] desktop]# bash a.sh1 2 3 4 5The current script name is a.sh a total of 5 parameters, namely 12 3 4 5. The 1th parameter is 1, and the 3rd is 3. 

3, judge the user's parameters

The conditional test syntax in the shell script can determine if the expression is true, and returns the number 0 if the condition is true, otherwise it returns other random values. Remember that there should be a space on both sides of the conditional expression.

Parameters used for file testing

Operator Role
-D Test whether the file is a directory type
-E Test whether the file exists
-F Determine if it is a generic file
-R Tests whether the current user has permission to read
-W Tests whether the current user has permission to write
-X Tests whether the current user has permission to execute

The following uses the file test statement to determine if/etc/haha is a directory-type file, and then through the shell interpreter inside the $? The variable displays the return value after the previous command was executed. If the return value is 0, the directory exists, or if the return value is nonzero, it means that the directory does not exist:

[Email protected] desktop]# [-d/etc/haha][[email protected] desktop]# echo $? 1

Logical statements are used for logical analysis of test results, and different effects can be achieved based on test results. For example, in the shell terminal, the logical "and" operation symbol is &&, which means that the command after the previous command execution succeeds,

Determine if the/etc/passwd file exists, and if so, output exist

" exist " exist

In addition to the logical "and", there is also the logical "or", its operation symbol in the Linux system is | |, indicating that after the previous command failed to execute the command after it

Determine if the/etc/haha file exists, does not exist, and the output is not exist

" Not exist " Not exist

The third logical statement is "non", and the operation symbol in the Linux system is an exclamation mark (! ), which represents the inverse value of the judgment in the condition test. That is, if the result of the original test is correct, it becomes wrong, and the result of the original test error turns it into the correct one.

Determines whether the current user is a non-administrator user. Because the judgment result is correct due to two negation, the preset information is output normally

" Administrator " Administrator

The following example is executed in order to determine whether the user variable name of the current logged-on user is equal to root, and then use the logical operator "non" to reverse the operation, the effect becomes to determine whether the currently logged on users are non-administrator users. Finally, if the condition is set, the user typeface will be output according to the logical "and" operator, or if the condition is not satisfied, the word "root" will be output through the logical "or" operator, and if the previous && is not established, then the following | | Symbol.

" User " " Root " Root

An integer comparison operator is only an operation on numbers, cannot manipulate numbers with strings, files, and so on, and cannot be taken for granted by using the equals sign, greater than sign, less than, etc. in everyday life. Because the equals sign conflicts with an assignment command, the greater-than and less-than-sign conflicts with the output redirection command and the input Redirection command, respectively. So be sure to work with the canonical integer comparison operator

Available integer comparison operators

Operator Role
-eq is equal to
-ne is not equal to
-gt is greater than
-lt is less than
-le is equal to or less than
-ge is greater than or equal to

Test if 10 is greater than 10 and 10 equals 10.

Ten Ten ][[email protected] desktop]# echo $? 1  Ten  ][[email protected] desktop]# echo $? 0

A string comparison statement is used to determine whether a test string is a null value, or whether two strings are the same. It is often used to determine whether a variable is undefined (that is, the content is null), and it is easier to understand.

Common string comparison operators

Operator Role
= Compare strings for the same content
!= Compare strings for different content
-Z Determines whether the string contents are empty

The next step is to determine if the variable is defined by determining whether the string variable is a null value.

[[Email protected] desktop]# [-z $String][[email protected] desktop]# echo $? 0

4. Process Control Statements

If condition test statement

The IF condition test statement allows the script to automatically execute the corresponding command according to the actual situation. From a technical point of view, if statements are divided into single-branch structure, double-branch structure, multi-branch structure, and its complexity increases along with the degree of flexibility.

The single branch structure of the IF condition statement consists of the IF, then, and FI keywords, and executes the preset commands only after the condition is established, equivalent to the colloquial "if ...". So ... ".

The following uses a single-branch if condition statement to determine if the/etc/haha file exists, if there is a end condition and the entire shell script, and vice versa to create this directory

[[email protected] desktop]# Vim a.sh #!/bin/bashdir="/etc/haha"if [!--/etc/

If the two-branch structure of the statement is composed of if, then, else, fi keyword, it makes a conditional matching judgment, if the conditions match, then to execute the corresponding preset commands, and vice versa to perform the default command, equivalent to the colloquial "if ... So...... Or...... So ... ".

The following uses the double-spoke if condition statement to verify that a host is online, and then either displays the host online information or the host's online information based on the result of the return value. The script here mainly uses the ping command to test the network connectivity with the other host, while the ping command in the Linux system does not attempt to end like Windows 4 times, so in order to avoid the user waiting too long, you need to pass the-c parameter to specify the number of attempts, and use the-I parameter to define the send interval for each packet, and to use the-W parameter to define the wait time-out.

[email protected] desktop]# Vim a.sh #!/bin/bashping-C3-I.0.2-W3$1&>/dev/NULL # &>/dev/null indicates that standard output and error messages are entered into a file,/dev/null is a file called a Linux black holeif[$?-eq0]thenecho"Host is on-line."ElseEcho"Host is off-line."fi[[email protected] desktop]# bash a.sh192.168.10.10Host192.168.10.10  isOn-line.

If the multi-branch structure of the statement is composed of if, then, else, elif, fi keyword, it makes multiple conditional matching judgment, this multiple judgment of any one of the successful match will execute the corresponding preset command, equivalent to the colloquial "if ... So...... If...... So ... ".

The following uses the multi-branch if condition statement to determine the score in which the user input scores range, and then output such as excellent, Pass, fail and other information. In a Linux system, read is a command to read user input information, to assign the received user input information to the following specified variable, the-p parameter is used to display a certain hint message to the user. In the following script example, only if the user enters a score greater than or equal to 85 points and less than or equal to 100 points, the output of the excellent typeface; If the score does not satisfy the condition (that is, the match is unsuccessful), then continue to determine whether the score is greater than or equal to 70 points and less than or equal to 84 points If it fails twice (that is, two matches fail), the output fail word

[email protected] desktop]# Vim a.sh #!/bin/Bashread-P"Enter you score:"Gradeif[$grade-ge -]&&[$grade-le - ] ; Thenecho"$grade is excellent"Elif [$grade-ge -]&&[$grade-le - ] ; Thenecho"$grade is Pass"ElseEcho"$grade is Fail"fi[[email protected] desktop]# bash a.sh Enter you score: the the  isexcellent[[email protected] desktop]# bash a.sh Enter you score: + +  ispass[[email protected] desktop]# bash a.sh Enter you score: About About  isFail
View Code

For Condition Loop statement

The For Loop statement allows the script to read multiple messages at once, then manipulate the information one at a time, using a For loop statement when the data to be processed has scope.

Have the script automatically read the host list from the text, and then automatically test the hosts individually.

[email protected] desktop]# vim ip.txt192.168.10.10192.168.10.11192.168.10.12#!/bin/bashlist=$ (cat/root/desktop/ip.txt) forIpinch$list DoPing-C3-I.0.2-W3$ip &>/dev/NULLif[$?-eq0 ] ; Thenecho"Host $ip is on-line."ElseEcho"Host $ip is off-line."fidone[[email protected] desktop]# bash a.sh Host192.168.10.10  ison-Line . Host192.168.10.11  isoff-Line . Host192.168.10.12  isOff-line.
View Code

The $ (command) that appears in the script is equivalent to ' command '

While conditional loop statement

A while conditional loop statement is a statement that allows a script to repeat commands based on certain conditions, and its looping structure often does not determine the number of final executions before execution, completely different from the target, scoped usage scenario in the FOR Loop statement. The While loop statement determines whether to continue executing the command by judging the true or false of the condition test, and if the condition is true, the loop is closed for false.

Next, using the multi-branch if condition test statement with the while condition Loop statement, write a script guess.sh to guess the value size.

Use the $random variable to get a random value (in the range of 0~32767), take this random number to 1000 for the remainder operation, and use the expr command to get its results, and then use this value with the user through the Read command to enter the value of the comparison judgment. This judgment statement is divided into three cases, namely, to determine whether the value entered by the user is equal to, greater than, or less than the value obtained using the expr command. The exit 0 command is not run until the user enters a value equal to the value obtained by the expr command, terminating the execution of the script

#!/bin/Bashprice=$ (Expr $RANDOM% +) Time=0Echo"Game start!" while true DoRead-P"Enter Number:" int Let time++if[ $int-eq $price]; Thenecho"yes,the number is $int"Echo"You guess total $time"Exit0Elif [$int-GT $price]; Thenecho" High"ElseEcho" Low"Fidone

Each time you loop to the Let time++ command, the value in the time variable is incremented by 1 to count how many times the loop total executes

The expr command is an expression evaluation tool that uses it to perform the evaluation of an expression,

result= ' Expr 2 + 3 '

# echo $res

5

Shell programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: