Introduction to shell programming in Linux-general Linux technology-Linux programming and kernel information. For more information, see the following section. Generally, you can obtain a system response every time you input a command from the command line. Once we finally get the result by entering the command one by one, this is obviously inefficient. To achieve this goal, we usually use shell programs or shell scripts.
I. Introduction
Shell programming has many features similar to C and other programming languages, but it is not as complex as programming languages. A Shell program is a series of Linux commands and utilities in a file. During execution, each command is interpreted and executed one by one through Linux.
Let's look at a simple shell program:
1. Create a file named date with the following content and store it in the bin subdirectory under the directory.
# Program date
# Usageto: show the date in this way (note)
Echo "Mr. $ USER, Today is :"
Echo date "+ % B % d %"
Echo "Whish you a lucky day !"
2. After editing the file, it cannot be executed. We need to set the executable permission for it. Run the following command:
Chmod + x date
After the above process, we can execute this shell program like using the ls command.
[Beichen @ localhost bin] $ date
Mr. beichen, Today is:
January 13 Friday
Whish you a lucky day!
To execute this program in any directory, you can add the bin directory to the path.
(Note: $ HOME here replaces/home/beichen, while the bin directory is a self-built directory)
Another method for executing date is to pass it as a parameter to the shell command:
[Beichen @ localhost/] $ bash date
Mr. beichen, Today is:
January 13 Friday
Whish you a lucky day!
Although we used chmod + x date to set date to executable, it does not matter if it is not set, but it is executed in Linux, you must first tell the system that it is an executable script.
[Beichen @ localhost/] $. date
Mr. beichen, Today is:
January 13 Friday
Whish you a lucky day!
That is to say, add a dot "." Before date, and separate the space with the name of the shell script file. Of course, this is not recommended.
Ii. shell Parameters
Just as the ls command can accept directories and other parameters as its parameters, parameters can also be used in shell programming. Shell has location parameters and internal parameters.
1. location parameters
The parameters provided by the system are called location parameters. The value of the location parameter can be obtained using $ N. N is a number. If it is 1, it is $1. similar to the array in C language, Linux segments the input command string and marks each segment. The label starts from 0. The value 0th is the program name. It indicates the parameter passed to the program from 1. For example, $0 indicates the program name, $1 indicates the first parameter passed to the program, and so on.
2. Internal Parameters
In the above process, $0 is an internal variable, which is mandatory, while $1 is dispensable. There are several internal variables that are the same as $0.
$ # ---- Total number of parameters passed to the program
$? ---- When the previous code or shell program exits in the shell, if it Exits normally, 0 is returned, and vice versa.
$ * ---- A string consisting of all parameters passed to the program.
The following is an example:
Create a program P1 with the following content:
Echo "Program name is $0"
Echo "There are totally $ # parameters passed to this program"
Echo "The last is $ ?"
Echo "The parameters are $ *"
The execution result is as follows:
[Beichen @ localhost bin] $ P1 this is a test program // pass 5 parameters
Program name is/home/beichen/bin/P1 // give the complete path and name of the Program
There are totally 5 parameters passed to this program // The total number of parameters
The last is 0 // program execution result
The parameters are this is a test program // returns a string consisting of parameters
The following code uses internal variables and location parameters to compile a simple delete program named del:
# Name: del
# Author: liangnian
# This program to compress a file to the dustbin
If test $ #-eq 0
Then
Echo "Please specify a file !"
Else
Gzip $1 // first compress the file
Mv upload 1.gz $ HOME/dustbin // move to the recycle bin
Echo "File $1 is deleted !"
Fi
Iii. Variable expressions
In the small program we wrote above, we used a keyword test, which is actually an expression in the shell program? D? D comparison (test ). By combining the conditional statements such as if provided by shell (which we will introduce later), we can easily complete the judgment.
The usage is as follows:
Test expression
The operators represented by expressions include string operators, numeric operators, logical operators, and file operators. The file operator is a unique shell operator, because all the variables in the shell are strings. In order to perform operations on the file, such an operator is provided.
1. String comparison
Purpose: test whether the string is equal, whether the length is zero, and whether the string is NULL (Note: bash distinguishes between a zero-length string and a NULL String)
Common Character wear operators include:
= Compare whether two strings are the same. If they are the same, they are "yes "! = Compare whether two strings are the same. If they are different, the value is "yes"
-N indicates whether the length of a string is greater than zero. If the length is greater than zero, the value is "yes"
-Z: determines whether the wearing degree of a string is equal to zero. If it is equal to zero, it is "yes"
2. digit comparison
Unlike other programming languages, test statements are not used>? Similar symbols are used to represent the comparison of the size, but are expressed in an integer.
-Equal eq
-Ge is greater than or equal
-Le is less than or equal
-Ne is not equal
-Gt greater
-Lt is less
3. logical operation! Reverse: logical value opposite to a logical value
-A and (and): If the two logical values are "yes", the return value is "yes". Otherwise, the return value is "no"
-O or (or): if either of the two logical values is "yes", the return value is "yes"
4. File Operations
The file test expression is usually used to test the file information. It is generally determined by the script whether the file should be backed up, copied or deleted. Because there are many file operators in test, we only list some common operators.
-D the object exists and the returned value for the directory is "yes"
-F the object exists and the returned value is "yes"
-L the object exists and returns "yes" as the symbolic link"
-If the r object exists and is readable, the returned value is "yes"
If the-s object exists and the length is not zero, the returned value is "yes"
-If the w object exists and can be written, the return value is "yes"
-If the x object exists and is executable, the returned value is "yes"
File1? Cnt (-ot) file2 file 1 is newer than file 2 (old)
Iv. Loop Structure statements
Common shell loop statements include for loop, while loop, and until loop.
For Loop
Syntax: for variable in list
Do
Operation
Done
Note: The variable is used inside the loop to refer to the object in the List currently referred.
The list is the object to be operated inside the for loop. It can be a string or a file. If it is a file, it is the file name.
For example, delete all .gz files in the garbage box.
# Delete all file with extension of "gz" in the dustbin
For I in $ HOME/dustbin/*. gz
Do
Rm? Cf $ I
Echo "$ I has been deleted !"
Done
The execution result is as follows:
[Beichen @ localhost bin] $. f_rmgz
/Home/beichen/dustbin/nessus-4.0.0.2.tar.gz has been deleted!
/Home/beichen/dustbin/gftp-2.2.1.tar.gz has been deleted!
While Loop
Syntax: while expression
Do
Operation
Done
As long as the while expression is true, the operation between do and done will continue.
Until Loop
Syntax: until expression
Do
Operation
Done
Repeat the operations between do and done until the expression is true.
Example:
# Test
# Add from 1 to 100
Total = 0
Num = 0
Until test num? Ceq 100
Do
Total = 'expr $ total + $ num' // note that the quotation marks here are backticks, the same below
Num = 'expr $ num + 1'
Done
Echo "The result is $ total"
The execution result is as follows:
[Beichen @ localhost bin] $
The result is 5050!
5. Condition statements
The condition statements in Shell programs mainly include the if statement and the case statement;
If statement
Syntax: if expression 1 then
Operation
Elif expression 2 then
Operation
Elif expression 3 then
Operation
.....
Else
Operation
Fi
In Linux, the if end mark is to write the if statement in turn as fi, while elif is short for else if.
In theory, there can be an infinite number of elif instances.
Case statement
Syntax: case string in
Value 1 | value 2)
Operation ::
Value 3 | value 4)
Operation ::
Value 5 | value 6)
Operation ::
*}
Operation ::
Esac
The role of case is to execute the operation after the value when the string is the same as a value. If the same operation has multiple values, use "|" to separate the values. At the end of each case operation, there are two ":" And a semicolon is required.
Example:
Case $ USER in
Beichen)
Echo "You are beichen !";;
Liangnian)
Echo "You are liangnian"; // note that there is only one semicolon
Echo "Welcome !";; // Here are two semicolons
Root)
Echo "You are root! : Echo Welcome !";; // Write the two commands in one line and use a semicolon as the Separator
*)
Echo "Who are you? $ USER ?";;
Esac
Execution result:
[Liangnian @ localhost bin] $ test
You are liangnian
Welcome!
There are so many basic things about shell programming. If you want to learn more about shell programming, read related books.
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.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service