Source: gnu
Code: ------------------------------------------------ -------------------------------- 1. Establish and run the shell program
What is the shell program? Simple SHELL program is a row
SHELL or Linux command file.
Like a program to write a high-level language, write a shell program that requires a text editor. Such as VI, etc.
In the text editing environment, enter some shell / linux command line according to the syntax rules of the shell, form a complete
Program file.
There are three ways to perform the shell program file.
(1) #CHMOD X File
(2) #SH file
(3) #. File
When writing shells, the first line must indicate that the system requires that shell explains your shell programs, such as: #! / Bash,
#! / bin / csh, / bin / tcsh, or #! / bin / pdksh.
2. Variables in SHELL
(1) Common system variables
$ #: Save the number of programs command line parameters
$?: Save the return code of the previous command
$ 0: Save program name
$ *: Save all input command line parameters in the form of ("$ 1 $ 2 ...")
$ @: Save all input command line parameters in the form of ("$ 1" $ 2 "...)
(2) Define variables
The shell language is a non-type interpreted language. It is not like programming the variable in advance when programming with C / Java language. give one
A variable assignment, actually defines a variable.
In all shells supported by Linux, you can use assignment symbols (=) to assign values.
Such as:
ABC = 9 (Bash / PDKSH cannot leave space on both sides of the equal sign)
SET ABC = 9 (TCSH / CSH)
Since the variable of the shell program is not type, the user can store the character when the same variable is stored.
Integer.
Such as:
Name = ABC (Bash / PDKSH)
Set name = ABC (TCSH)
After the variable is assigned, you only need to add a $ set in front of the variable.
Such as:
Echo $ ABC
(3) position variable
When running a shell program that supports multiple command line parameters, the values of these variables will be stored in position variables, respectively.
Where the first parameter is stored in the position variable 1, the second parameter is stored in the position variable 2, and the secondary push ..., shell reserved
These variables do not allow users to define them in a way. The same variable is quoted by the $ symbol.
3. How to use the quotation marks in the SHELL
Shell uses quotation marks (single / double quotes) and backslash ("/") to shield some special characters to the Shell interpreter.
The reverse quotation marks (") have special significance to the shell.
Such as:
ABC = "How are you" (Bash / PDKSH)
SET ABC = "How are you" (tcsh)
This command line consists of the string HOW Are you which consists of three words as an overall assignment to the variable ABC.
ABC1 = '@ logname, how are you!' (Bash / PDKSH)
SET ABC1 = '$ logname, how are you!' (tcsh)
ABC2 = "$ logname, how are you!" (Bash / PDKSH)
Set abc2 = "$ logname, how are you!" (TCSH)
The logname variable is to save the current user name's shell variable, assume his current value: wang. After executing two commands,
The content of ABC1 is: $ logname, how are you !. The content of ABC2 is; Wang, How are you !.
Like single quotes, the antilactors can block all special characters. But he can only block a character at a time. Not to block
A set of characters.
The function of the reverse rating is different from the above three symbols. He does not have the function of blocking special characters. But you can pass him
The running result of a command is passed to another command. Such as:
Contents = `LS` (Bash / PDKSH)
SET Contents = `LS` (TCSH)
4. Test command in the SHELL program
In Bash / PDKSH, the command TEST is used to calculate a value of a conditional expression. They often in the conditional statements and loops
The statement is used to determine if certain conditions are met.
The syntax format of the TEST command:
Test Expression
or
[expression]
In the Test command, you can use a lot of SHELL internal operators. These operators are described below:
(1) String operator is used to calculate string expressions
TEST command | meaning
-----------------------------------------
STR1 = STR2 | When STR1 is the same as STR2, return TRUE
Str1! = STR2 | When STR1 is different from STR2, return TRUE
Str | When Str is not empty character, return TRUE
-n str | Returns true when the Str is greater than 0
-z Str | When the length of the STR is 0, return TRUE
-----------------------------------------
(2) Integer operators have functions similar to character operators. But their operation is for integers
TEST expression | meaning
---------------------------------------------
INT1-EQ INT2 | When INT1 is equal to INT2, return TRUE
INT1 -GE INT2 | When INT1 is greater than / equal to INT2, return TRUE
INT1 -LE INT2 | When INT1 is less than / equal to INT2, return TRUE
INT1-GT INT2 | When INT1 is greater than INT2, return TRUE
INT1-NE INT2 | When INT1 is not equal to INT2, return TRUE
-----------------------------------------
(3) The operator used for file operations, they can check: if the file exists, file type, etc.
TEST expression | meaning
------------------------------------------------
-d file | Returns true when File is a directory
-f file | Returns true when File is a normal file
-r file | Returns true when File is a read file
-s file | Returns true when the File file is greater than 0
-w File | Returns true when File is a writable file
-x file | Returns true when File is an executable file
------------------------------------------------
(4) SHELL logical operator is used to modify the expression of integer, string, file operator
TEST expression | meaning
-------------------------------------------------- ------------
! EXPR | Returns true when the value of EXPR is False
EXPR1 -A EXPR2 | When EXPR1, EXPR2 value is TRUE, return TRUE
EXPR1 -O EXPR2 | When the value of EXPR1, EXPR2 is at least one of True, return TRUE
-------------------------------------------------- ---------
note:
TCSH shell does not use Test commands, but the expression in TCSH can also bear the same function. TCSH
Supported expressions are the same in the expression in C. Usually in the IF and While commands.
TCSH expression | meaning
-------------------------------------------------- -----
INT1 <= INT2 | When INT1 is less than / equal to INT2, return TRUE
INT1> = INT2 | When INT1 is greater than / equal to INT2, return TRUEINT1 INT1> INT2 | Returns true when INT1 is greater than INT2 STR1 == STR2 | When STR1 is the same as STR2, return TRUE Str1! = STR2 | When STR1 is different from STR2, return TRUE -r file | Returns true when File is a readable file -w File | Returns true when File is a writable file -x file | Returns true when File is an executable file -e file | Returns true when File exists -o file | Returns true when the owner of the File file is the current user -z file | When the FILE length is 0, return true -f file | Returns true when File is a normal file -d file | Returns true when File is a directory EXP1 || EXP2 | Returns true when EXP1 and EXP2 value is at least one TRUE EXP1 && EXP2 | Returns True when the value of EXP1 and EXP2 is TRUE ! EXP | Returns true when EXP's value is false 5. Conditional statement Like other high-level language programs, branch and loop control structures are often used in complex shell programs. Bash, PDKSH and TCSH have two different forms of conditional statements: if statements and CASE statements. (1) IF statement Grammar format: Bash / PDKSH usage: IF [expression1] THEN Commands1 Elif [Expression2] Commands2 Else Commands3 IF TCSH usage: IF (Expression1) THEN Commands1 Else IF (Expression2) Then Commands2 Else Commands3 ENDIF Meaning: When the condition of Expression1 is True, the shell executes the commands1 command behind the THEN; Expression1's condition is false and the condition of Expression2 is satisfied when True Commands2 command; when the condition value of Expression1 and Expressin2 is False, the shell executes Commands3 command. IF statement ends with his counter-write Fi. (2) CASE statement The CASE statement requires the shell to compare a string S with a set of string modes P1, P2, ..., PN, when S is When a mode PI wants to match, the corresponding part of the program / command. SHELL's CASE statement is characterized The pattern can be included in the pattern * such a wildcard. Grammar format: Bash / PDKSH usage: Case string1 in STR1) Commands1 ;; STR2) Commands2 ;; *) Commands3 ;; ESAC TCSH usage: Switch (string1) Case str1: Statements1 Breaksw Case str2: Statements2 Breaksw DEFAULT: Statements3 Breaksw Endsw Meaning: The shell compares the string String1 and string mode STR1 and STR2. If string1 matches STR1, Shell executes command / statement of Commands1; if string11 and str2 match, the shell executes commands of Commands2 / Statement. Otherwise, shell will execute the program / command of Commands3. Among them, each branch program / command must be two The semicolon (;;) ends. 6. Circular statement A loop statement is used when needed for some operations that need to be repeated. (1) for statement Everyone knows that in many programming languages is the most common. It is no exception in shell. Thefor statement requires the shell to contain A set of commands in this statement performs a certain number of times. Grammar format: Bash / PDKSH Usage 1: For var1 in list DO Commands DONE Meaning: In this FOR statement, corresponding to each value in the list, the shell will execute a group of commands representing a Commands representative. In each execution of the entire cycle, the variable var1 will rely on the different values in the LIST. Usage 2: For var1 DO Setatements DONE Meaning: In this For statement, the Shell performs a group of Statements representatives for each item in variable var1. Command. When using this form of statement, the shell considers that all position variables are included in the VAR1 variable, and the location variables are Store the command line parameter value of the program. That is to say, he is equivalent to the following form: For var1 in "$ @" DO Statements DONE TCSH usage: There is no for for the word in tcsh, and the otherth is the foreach statement with the FOR statement. Foreach name (list) Commands end Example: For file; bash / pdksh DO TR A-Z A-Z <$ file> file.caps DONE #; TCSH Foreach File ($ *) TR A-Z A-Z <$ file> $ file.caps end (2) While statement The While statement is another loop statement provided by the shell. While statement specifies an expression and a set of commands. The statement makes the shell repeatedly executed a set of commands until the value of the expression is false. Grammar format: While Expression; BASH DO Statements DONE While (Expression); TCSH Statements end Example: Count = 1; BASH While [-n "$ *"] *** DO echo "this is a parameter Number $ COUNT $ 1" Shift Count = 'expr $ count 1' DONE Set count = 1; TCSH While ("$ *"! = "" ") echo "this is a parameter Number $ COUNT $ 1" Shift Set count = 'expr $ count 1' end The function of the SHIFT command in the statement is to pass all command line parameters. (3) Until statement Until and WHILE statements have similar syntax formats and functions, and different is that the value of Expression in the while is TRUE. The shell executes the command group; and when the value of the expression is false, the shell executes the set of commands. Grammar format: Until Expression DO Commands DONE Example: Count = 1 Until [-z "$ *"] *** echo "this is a parameter Number $ COUNT $ 1" Shift Count = 'expr $ count 1' DONE Love is noted in the above example. In the case of the expression: -n string, his meaning is when String is not empty When string, the value of the expression is true; the expression in the untricil: -z string, his meaning is when String is empty When the string, the value of the expression is true. It can be seen that the settings of the two programs are just the opposite. (4) SHIFT statement BASH and TCSH support SHIFT commands. SHIFT stores command line parameters in the position variable, transmit it to left. For example, The current value of the position variable is: $ 1 = file1 $ 2 = file2 $ 3 = file3 After executing the Shift command, the value of the position variable is: $ 1 = file2 $ 2 = file3 You can also specify the number of positional variable transfer in the Shift command, such as: Shift n example: While ["$ 1"] DO IF ["$ 1" = "- i"] THEN INFILE = "$ 2" SHIFT 2 Else IF ["$ 1" = "- o"] THEN Outfile = "$ 2" SHIFT 2 Else Echo "Program $ 0 Does Not Recognize Option $ 1" Fi DONE TR A-Z A-Z <$ Infile> $ OUTFILE (5) SELECT statement The SELECT statement is a unique loop statement provided by PDKSH. He is different from the circulatory statement introduced. He is not Repeatedly calculate a conditional expression and determine if a set of commands is executed in accordance with the value of the expression. The function of SELECT is automatic. Generate a simple text menu. Grammar format: SELECT MENU [in list_of_Items] DO Commands DONE Meaning: When performing a SELECT statement, PDKSH creates a menu for members of each column in list_of_items, respectively. Option .list_of_items can be either a variable containing multiple options, or a set of options listed in the program If a list_of_items is not provided in the statement, the SELECT statement will use the position variable as List_OF_Items. Example: Select Menuitem in Pick1 Pick2 Pick3 DO echo "Are you have you want to pick $ menuitem" Read res; Receive the user's input and store the input value in a specific variable. IF [$ RES = "Y" -o $ res = "y"] THEN Break; used to exit when cyclic statements such as While, For, SELECT Fi DONE (6) REPEAT statement The REPEAT statement is a unique loop statement provided by TCSH. Use the REPEAT command to ask the shell to perform certain commands The number of times. Grammar format: Repeat Count Command Such as; Foreach Num ($ *) REPEAT $ Num Echo -n "*" echo "" end 7. Sore in SHELL Shell allows users to define their own functions. The function is an important structure in the advanced language. The functions in the SHELL are in C or other The function defined in the language is the same. Compared with the beginning of the head, a line is written, the main benefits of using the function is conducive to the organization. The whole process. In Bash, a function of the syntax format is as follows: FName () { Shell Comads } After defining a function, you need to call them in the program. The format of the function in thebash: FName [Parm1 Parm2 Parm3 ...]]] When calling a function, you can pass any multiple parameters to the function. The function will see these parameters as being stored in his command line parameters. Location variable. Example: This program defines 4 functions: Upper (): Converts the letters passing into his file to uppercase and store the end of the same name for .out. Lower (): Converts the letters passing to his file into lowercase and stores the end of the same name for .out. Print (): The output is passed to the content of the file. USAGE_ERROR (): Help information for the output. The master module of the program is a case condition statement. He determines the function to complete according to the first parameter in the command line, and call the corresponding The function completes this feature. Upper () { Shift For i DO TR A-A A-Z <$!> $ 1.out RM $ 1 MV $ 1.out $ 1 Shift DONE; Lower () { Shift For i DO TR A-Z A-Z <$ 1> $ 1.out RM $ 1 MV $ 1.out $ 1 Shift DONE; PRINT () { Shift For i DO Lpr $ 1 Shift DONE; USAGE_ERROR () { Echo "$ 1 SYNTAX IS $ 1" echo "" Echo "Where option is one of the folowing" Echo "P - to Print Frame Files" Echo "U - To Save As Uppercase" Echo "L - to Save as LowerCase"; Case $ 1 in P | -p) Print $ @ ;; u | -u) Upper $ @ ;; l | -l) Lower $ @ ;; *) USAGE_ERROR $ 0 ;; ESAC -------------------------------------------------- ---------------------------- to sum up Using Shell Programming is an important means to improve system management work efficiency, learn the shell and understand the basic command and management of system The method of use of tools is equally important! Attachment: A.bash common commands Command | meaning -------------------------------------------------- ----------------------------- Alias | Settings command alias BG | Execute a hang-haunged process in the background CD | Change the user's current directory EXIT | Termination of a shell Export | Make the variables of the parameters of this command and its current value, visible in the child process of the current running shell FC | Edit the current list of historical lists FG | Let a hang-haunted process in the front desk Help | Display help information for BASH internal commands History | Display a certain number of command lines recently entered Kill | Termination of a process PWD | Display User Current Work Contents UNALIAS | Delete Command Division Name -------------------------------------------------- ------------------------------ System variables used in Bash Variable | meaning -------------------------------------------------- ----------------------------- Editor, Fcedit | Bash's FC Command's Default Text Editor Histfile | Specify the name of the recently entered command line file Histicsize | Specify the size of the command line history file HOME | Current user's host directory OldPWD | User's previous directory PATH | Specify the path to search when Bash finds executable PS1 | Command Line Environment Displays the first level prompt symbol PS2 | Command Line Environment Displays the second level prompt symbol PWD | User Current Work Contents Seconds | The runtime (in seconds) of the currently running Bash process)