Shell Programming
* SHELL is? Any inventions have an interface for users. The interface for users is used by the user is the shell (DOS's Command, but UNIX is much more powerful). The shell provides users with input commands and parameters and get the environments where command execution results. For different needs, UNIX provides different shells. Most of UNIX support Bourneshell. The following tutorials take Bourneshell (BSH) as an example, step by step to experience the powerful features of UNIX shell, to achieve more convenient and flexible management, apply Unix purposes. 1. The UNIX kernel and the SHELL interaction method starts UNIX, the program UNIX (kernel) will be transferred to the computer memory and keep it in memory until the machine is turned off. During the boot process, the program init will enter the background run until the machine is turned off. The program query file / etc / inittab, which lists the individual ports and features of the connection terminal. When an active terminal is found, the init program calls the Getty program to display login information on the terminal. (UserName and Passwd) After entering the password, getty calls the Login process, which verifies the user's identity according to the content of the file / etc / passwd. If the user passes authentication, the Login process sets the user's Home directory to the current directory and handles the control to a series of setup programs. The Setup program can be a specified application, usually the setup program is a shell program, such as: / bin / sh, Bourne Shell (Command is out, huh). After getting control, the shell program reads and executes files /etc/.profile and .profile. These two files have established a system-wide and the user's own work environment. Final shell displays the command prompt, such as $. (This is a BSH as an example, if csh, for .cshrc, ksh is .kshrc, bash is .bashrc, etc.) note to see /etc/.profile and .profile as a DOS autoeexec.bat or config.sys file When the shell exits, the kernel control is handed over to the init program, and the program restarts the automatic login process. There are two ways to make the shell exit. First, the user performs the exit command, and the other is the kernel (for example, the root uses the kill command) to issue a kill command to end the shell process. After the shell exits, the kernel reclaims the resources used by the user and the program. After the user logs in, the user command is the relationship between the computer interaction: command process ---> shell program ---> UNIX kernel ---> Computer hardware. When the user enters a command, such as $ LS, the shell will locate its executable file / bin / ls and pass it to the kernel. The kernel generates a new sub-process call and execute / bin / ls. When the program is executed, the kernel cancels the child process and handles the control to its parent process, the shell program. For example, the execution: $ PS This command will list the processes that the user is performing, that is, the shell program (discussed in detail, an urgent needs now) and the PS program. If you do: $ SLEEP 10 & $ PS, the first command will generate a Sleep child process executed in the background. The sub process is displayed when the PS command is executed. Whenever the user performs a command, a child process is generated. The execution of the sub-process is completely independent of its parent process or shell, which makes the shell to do other work. (Shell just tells the kernel's intent, then what should you do?) Now Windows has a planned task (in a fixed time, the date is automatically executed with a task), in fact, UNIX has this feature very early, that is, the so-called The automatic execution of the shell.
Some UNIX resources, such as CRON can automatically execute the shell program without the need for users, (this function is in / var / spool / crotab directory). The CRONTAB program is very useful for system administrators. The cron service is used to operate at a specific time (month, day, week, time, minute). We take root 's crontab as an example. The root user's crontab file is placed in / var / spool / crontab / root, its format is as follows: (1) (2) (3) (4) (5) (6) 0 0 * * 3 / usr / bin / updatedb 1. Minute (0-60) 2. Hours (0-23) 3. Day (1-31) 4. Month (1-12) 5. Week (1-7) 6. The program to run 2.shell Function and Features 1> Command Line Explanation 2> Using the Reserved Word 3> Using the Shell Element Character (Wi - Caracoring) 4> Processor Command 5> Using Input Output Redirection and Pipe 6> Maintain Some Variables 7> Operation Environment Control 8> Support Shell Programming is not more to say "command line interpretation", just enter a line unix command after the shell prompt (for example, "$", "%", "#", etc., and the shell will receive the user's input. "Use the reserved word": shell has some words with special meaning, such as in the shell script, DO, DONE, FOR et al. To control cycle operation, if, then and other control condition operations. Reserving the word difference with the shell environment. "Tongcar": * Matched any location? Match a single character [] matching character range or list, for example: $ ls [ac] * will list all files at the beginning of the AC range $ ls [A, M, T] * All file "program commands" starting with E, M or T: After the user enters the command, the shell read the environment variable $ PATH (which is typically set in the user's own .profile), the variable contains the command executable A list of directory where files may exist. The shell looks for the executable corresponding to the command from these directories, and then gives the file to the kernel. "Input Output Redirection and Pipes": Redirected functionality with DOS Redirect function: ">" Redirect Output "<" Redirect input and pipe symbols, is a powerful place for UNIX function, symbol is a vertical line: "|", Usage: Command 1 | Command 2 His function is to pass the result of the first command COMMAND 1 to Command 2, for example: $ ls -s | sort -nr | pg All files in the current directory and give the output to the sort command as input, and the sort command sorts the output of the LS by digital decreasing order. Then transmit the sorted content to the PG command, the PG command displays the sort commands on the display. "Maintenance Variable": The shell can maintain some variables. Some data is stored in the variable.
Users can assign values to variables with "=", such as: $ look = / usr / mydir This command establishes a variable named LOOKUP and assigns value / usr / mydir, and the user can use Lookup in the command line to replace / usr / mydir, for example: $ Echo $ LOOKUP results show: / usr / mydir In order to make the variable can be used by the sub-process, you can use the exprot command, for example: $ =UP = / usr / mydir $ export lookup "Run Environment Control": When the user logs in to start After the shell, shell wants to create a job for the user, as follows: 1> When the login program activates the user shell, the environment variable will be established for the user. Read from the / etc / profile and .profile file, in these files, the terminal type is typically used in these files, and set the shell to look for the path to the executable with the $ terminal variable. 2> When the shell is started from the / etc / passwd file or the command line, the user can specify some parameters to the shell program, such as "-x", which can display the command and its parameters before command execution. These parameters are described later. "Shell Programming": The content mainly introduced in this article. The shell itself is also a language (* can be understood as a combination of UNIX commands, plus the category of class C, cycle control statement, similar to DOS batch, but strong), users can program (script, Text file), complete a specific job. Shell Variables Let's introduce the Bourne Shell program: Bourne Shell has been designed since the Bell Lab. Since then, many vendors have designed many versions of UNIX based on different hardware platforms. But in many versions of UNIX, the Bourne Shell has been consistent. 1> BSH start: After the user is logged in, the system launches the Shell according to the information item of the user according to the file / etc / passwd. For example, the information item in PassWD is: ICE_Walk411: 103: ICE_Walk: / BSH indicates that the username is ICE_walk and other information, in the last item "/ bin / bsh" indicates the user The SH environment is BSH, so the system is started. You can use the following parameters during starting or execution (including the shell program - scripting) that we want to talk about, we can explain: -a Read all variables-C "string" reads commands from String - E use Non-interactive mode -F prohibits the SHELL file name Generate -h definition -i interactive mode -k to execute setting options - N read commands but do not perform -R Limited mode -s command from standard input -T -T Execute a command, then exit the shell -u in replacement, use unset variables will be erroneous-V. Mixed's input line -X tracking mode, and the execution command Many modes can be combined, you can try it, But -ei is not like, do you say why? Use SET to set or cancel the shell option to change the shell environment. Open the option "-", close the option " ", most UNIX allows you to turn the A, F, E, H, K, N, U, V, E, H, K, N, U, V, and X options are allowed to open or close. If you display the option already set in the shell, do: $ Echo $ - BSH has a .profile file in the Home directory of each user, you can modify the file to modify the shell environment.
In order to add a path of executable file (such as / ice_walk / bin), you can add the following code to Path = $ PATH: / ICE_Walk / Bin; Exprot Path .profile meaning the environment variable in the SHELL is as follows: CDPATH executes a CD command Search Path HOME User's Home Directory IFS IFS The domain segmentation of the IFS, generally a space character, a tab, or a newline mail specifying a specific file (mailbox) path, there is a Search path for using the PATH search command (With the DOS config.sys PATH) PS1 master command prompt, the default is "$" PS2 from the command prompt, the default is ">" TERM Using Terminal Type 2> BSH Special Character and its meaning in BSH Non-alphabetic characters. The use of these characters is divided into four categories: as a special variable name, generate file name, data or program control, and reference and escape character control. They allow users to complete complex tasks using the least code of the shell. *> SHELL Variable Name Used Special Character $ # Transfer to the Parameter Serial No. $ of the Command SHELL $ - Provides an option $ when the shell starts or uses the set command? The value returned after the last command is executed $$ Current shell process number $! A child process number $ @ All parameters, each parameter is included in brackets, enclose the $ n position parameter value with double brackets, n Represents $ 0 Current shell name *> Special Characters include "*", "?", "[]", Taking above, no longer said. *> Data or Program Control Used Special Character> (File) Output Redirection to the file (Created, Overwrite without File) >> (File) Output Redirection to the file (not created, there is an additional to Document Tail) <(file) Enter the redirection to the file; Command Solution | Pipes & Background Run (for example: Sleep 10 & `` command replace, redirect output of a command as another command *> For reference or Escape Special Character BSH Use Single Quotes '' and Double Quotes "" to form a simple data string with a blank separated word. The difference between the use of single quotes and the double quotes is the content in the dual quotation. And variables. Escape characters are also the same. $ Echo "$ home $ path" results show $ / u / ice_walk / bin: / etc: / usr / bin and $ Echo '$ home $ path' results Show $ HOME $ PATH shell The escape is a "/", indicating that the following characters do not have special meanings or not the SHELL function $ ECHO / $ HOME $ PATH results show $$ Home / bin: / etc: / usr / bin: 3> BSH In front of us, we reference variables in multiple places. When the shell encounters a "$", it will think it will be a variable, regardless of whether the variable is environment variable or user-defined Variables, variable names in the command line are replaced by variable values. For example, the command: LS $ Home will list the files in the Directory corresponding to the directory. Users can replace anywhere in the command line.
Includes command name itself, for example: $ dir = ls $$ dir f * will list files starting with F. Now introduce the variable of BSH. There are four types of variables in BSH: user-defined variables, position variables (shell parameters), predefined variables and environment variables. User-defined variable: user-defined variable consists of letters and underscores, and the first character of the variable name cannot be numbers (0 ~ 9). Like other UNIX names, the variable name is sensitive. The user can assign a value to the variable on the command line, for example: $ name = ICE_walk assignment to Ice_walk, when applying the variable Name, before NAME, "$", the previous, no longer Don't say much nonsense, the key is to have a teacher). You can use variables and other characters to make new words, for example: $ sun = sun $ echo $ {sun} day When using shell variable, you can add {} on the variable name on both sides of the variable name, with more clear display to the shell, Which is a true variable to achieve the combination of strings. The results show: Sunday (Note You cannot Echo $ Sunday, because the Sunday variable is not defined, the reader test execution result) The user can also assign a value to multiple variables on the command line, assigning the statement to separate: $ x = x y = Y Note The value of the variable assignment is from the right to left, the value of Y $ x = z y = $ z y is empty (when the variable is not assigned, the shell does not report an error, but assignment The user can use the "Unset
$ echo hello $ uname results display: Hello $ Echo Hello $ {uname: = there} results show: Hello the $ echo $ uname results display: there is $ uname = john $ echo hello $ {uname: -there} results show: Hello The value of the John variable can also be `` enclosed command: $ userDir = {$ mydir: -`} The alternative method of the third variable is that only the specified value is replaced by the specified value when the variable has assigned: $ { VARIABLE: VALUE} Only when Variable is assigned, its value is replaced with Value, otherwise no replacement, for example: $ erropt = a $ Echo $ {Erropt: "Error Tracking is Acitive"}}} t TRACKING IS Acitive $ Erropt = $ {Erropt: "Error Tracking is Acitive"} The result is displayed: (empty) We can also use the error check condition to change: $ {variableMessage} When the variable variable is set, normal replacement . Otherwise, Message will be sent to standard error output (if this replacement appears in the shell program, then the program will terminate). For example: $ uname = $ echo $ {uname "uname Has NOT BEEN SET"} The result is displayed: Uname Has Not Been set $ uname = Stephanie $ Echo $ {UNAME "uname has not been set"} results show: Stephanie is not specified When Message, Shell will display a default message, for example: $ uname = $ echo $ {uname} results display: sh: uname: parameter null or not set 4> When the location variable or shell parameter is explained in the shell, Use the first word of the command line as a command, and other words as a parameter. These parameters are transmitted to the program as position variables when the executable of the command is a shell program. The first parameter is $ 1, the second is $ 2 .... ninth is $ 9. Where 1 to 9 are real parameter names, "$" is just a replacement of the variable. Location Variable $ 0 means the executable file name corresponding to the command. The location variable will be described in detail later. 1. Reemption Variable User After assigning the variable, in order to prevent the modification of the variable in order to prevent this variable to read-only variables: Readonly variable 2.export command shell When executing a program, first establish a program A new execution environment called a child shell. The variables in the Bourne Shell are part, that is, they are only meaningful in creating their shell. Users can use the export command to let the variables are identified by other child shells. However, the variable of a user cannot be used by other users. When the user starts a new shell, the shell will use the default prompt. Because the value assigned to the variable PS1 is only valid in the current shell.
In order to allow the child shell to use the prompt symbol defined in the current shell: $ ps1 = "Enter Command:" Enter Command: Export PS1 Enter Command: SH Enter Command: This time the variable PS1 becomes a global variable. It can be used by its son shell. When the variable is set to a global future, it will remain effective until the user exits the SHELL in which the variable is in. Users can give a variable permanently assigned to a file .profile. See "Specific Shell" for details. Basic statements From this section, we will introduce the basic knowledge of the shell program design, by writing a shell script, the user can have conditional or repeated execution commands according to their own needs. With the shell program, a single UNIX command can be combined into a fully utility tool to complete the user's task. 1> What is the shell program Enter a complex command in UNIX Shell, such as: $ ls -r / | greo myname | PG We can call users to program the shell, write this statement in a file And the file is permissions to the file, then the file is the shell program we traditionally said. 2> Simple shell program assumes that the user uses the following command to back up your own data files: $ cd / usr / icewalk; ls * | cpio -o> / dev / fd0 we can write it in a file, such as: Ba. SH: $ cat> ba.sh CD / USR / ICEWALK LS * | CPIO -O> / dev / fd0 ^ D (Ctrl_d) program ba.sh is the shell script, users can write more complex with VI or other editing tools script. At this point, the user's backup file only needs to execute the shell program ba.sh. When executed, you must create a child shell: $ SHBA.SH program SH when the user is logged in, but when the SH command belt Parameters BA After .sh, it will no longer be an interactive shell, but read the command directly from the file ba.sh. Another way to execute the command in ba.sh is to give file ba.sh execute permissions: $ chmod x ba.sh, the user can enter the file name ba.sh as a command to back up your own data, need attention Yes, when using this method to execute the command, the file ba.sh must exist on the path specified by the environment variable $ PATH. 3> Using data variables in Shell Use data variables in the shell, such as Ba.SH program: CD / USR / ICEWALK LS | CPIO -O> / dev / fd0, the directory to be backed up in this program is a constant amount, ie This program can only be used to back up a directory. If the variable is used in the program, it will make it more common: Workdir = $ 1 CD $ WORKDIR LS * | CPIO -O> / DEV / FD0 This change allows users to use the program backup variable $ WORKDIR specified by the program. For example, we have to back up the / home / www, just run the ba.sh / home / www. (If you don't understand $ 1, the pass of the shell parameter will be described in detail, and the first parameter of this SH program -Ba.sh) 4> In order to add the readability in the shell program, we advocate join Comment. Note in the shell program will start with "#". When the shell explains "#", it will be considered from the "#" number until the end of the row.
5> Motivation of the SHELL variable is a type of variable, that is, the variable will be limited to a certain data type, such as an integer or character type. The shell variable usually stores in characters. In order to arithmetic operations for the shell variable, the expr command must be used. The EXPR command will use an arithmetic expression as a parameter, usually as follows: Expr [Number] [Operator] [Number] Since the shell is stored in the form of character, the user must ensure that the operand to participate in the arithmetic operation must be a value. The following is an effective arithmetic operator: two integers add-the first number to reduce the second number * Two integer multiplication / first integer divided by the second integer% two integers, take the loser, for example : $ EXPR 2 1 results show: 3 $ EXPR 5 - 3 results show: 2 If a parameter of EXPR is a variable, then replace the variable name before the expression calculates. $ int = 3 $ expr $ int 4 results show: 7 Users cannot use "*" to make multiplication, if you enter: $ expr 4 * 5 system will report error, because shell see "*" will first perform file name replace. The correct form is: $ EXPR 4 / * 5 results show: More than 20 arithmetic expressions can be combined, for example: $ expr 5 7/3 results show: 7 calculation order is the addition and decrease after the multiplication, to change the operation Order, you must use "` ", such as: $ int =` expr 5 7` $ int / 3 results show: 4 or: $ expr `expr 5 7` / 3 results show: 4 6> To the shell Program Transfer Parameters A program can use two methods to get input data. First, use parameters when executed. Another method is to interactively obtain data. The VI Editor program can obtain data by interactive methods, while LS and EXPR acquire data from the parameters. The above two methods shell programs can be used. This section describes the shell program by interactively obtain parameters in the "Interactive Read Data" section. Transfer parameters to the Shell program through command line to expand the use of the program. Take the Ba.SH program mentioned above as an example: $ CAT> Re.sh CD $ WORKDIR CPIO -I dev / fd0 ^ D program RE.SH Restores all files for the ba.sh program backup. If only a specified file is restored from the floppy disk, you can use the file name as a parameter, passed to the shell program Re.sh: Program rewritten as follows: $ cat> Re2.sh CD $ WORKDIR CPIO -I $ 1 dev / fd0 ^ D Users can specify files to be recovered, such as FNAME $ RE2.SH FNAME This time the file fname is passed to Re2.SH, and the disadvantage of Re2.SH is to recover two or more files to be repeated. We can deliver uncertain parameters with $ 0 variables to procedures: $ cat> re3.sh CD $ WORKDIR CPIO -I $ * dev / fd0 ^ D We can restore multiple files, such as FName1, Fname2, FName3 $ Re3.SH fname1 fname2 fname3 (above the program RE.SH, RE2.SH, RE3.SH, assuming that the user has chmod, executable), because the variable that does not assign value can be treated as Null, so if it is the program RE3.SH is not executed Give the parameters, then an null value will be inserted into the cpio command. This command will restore all saved files.
Conditional judgment statement condition determination statement is a very important statement in programming language, the meaning of this statement is to perform a specified set of commands when a certain condition is satisfied. 1> IF - THEN statement format: if Command1 Ten Command2 Command3 FI --- (iF statement end) Command4 has a return state after each program or command execution, users can use shell variable $? To get this state. The IF statement checks the return status executed by the previous command, if the command is successfully executed, the command between THEN and FI will be executed. In the above command sequence, Command1 and Command4 have generally executed. If Command1 is successfully implemented, Command2 and Command3 will also be executed. Please see the following procedure: #unload -program to backup and remove files CD $ 1 LS -A | CPIO -O> / dev / mnT0 RM * After the program is backed up, remove the file, but when the cpio command cannot be executed successfully, RM The order is still deleted, we don't want this, in order to avoid this, you can use if - the statement: # - Uninstall and judgment Delete Programs CD $ 1 if LS -A | CPIO> / dev / mnt0 Then Rm * Fi The program deletes the file after the CPIO execution is successful. If the execution is not successful, we hope to get a prompt, the echo command in the SH can display the message to the user, and display the wrap, the above program can be written: # - Uninstall and judgment Delete Programs CD $ 1 if ls -a | cpio> / dev / mnt0 the echo "Positive Delete Files ..." RM * Fi Echo command can use some special escape characters to format the output, below is these characters and Meaning: / b Backspace / c Display Non-wrap / F On the start of the terminal on the start of the screen, display / N wrap / R carriage / T tab / V vertical tab / anti-flap / 0NNN 1, 2 or 3-digit 8 credit integer represents an ASCII code character 2> if - the ELSE statement does not have to say its role, other high-level languages, format is: if command1 Then Command2 Command3 Else Command4 Command5 Fi in this structure The Command1 is executed first. When Command1 is executed successfully, Command2 and Command3 will be executed, otherwise the Command4 and Command5 are executed to see the following programs: # 备 program CD $ 1 if ls -a | cpio -o> / dev / mnt0 Then Echo " Deleting source data ... "RM * Else Echo" tape backup failed! "Fi 3> TEST command for condition test if statement Control the execution of the command by the return status executed by the test command, to test other conditions, in the BSH can be used in the BSH. This command detects a certain condition that returns 0 when the condition is true, otherwise the non-zero value is returned. The TEST command can make the IF statement in the shell program like the conditional judgment statements in other program languages.
The use method of the test command is: Test Condition can be tested into 4 categories: 1) Test the relationship between two strings. 2) Test the relationship between the two integers. 3) Test if the file exists or has some state or attribute. 4) Test multiple conditions with (AND) or (OR) combinations. 1. Conditional statement >> Test statement 1> Test string relationship BSH puts all command lines and variables as strings. Some commands such as EXPR and TEST can operate characters as numbers. Also any number can also operate as a string. Users can compare both strings equal or inequality, or test whether a string is assigned. The operators of the string are as follows: STR1 = STR2 When two strings have the same content, the length is true STR1! = STR2 When the string Str1 and STR2 are true -N STR1 When the length of the string is greater than 0, it is true (string Non-empty) -Z STR1 When the length of the string is 0, true (empty strings) STR1 When the string STR1 is non-empty, not only the shell program can use Test to determine the condition, and the Test command can also be performed independently, such as: $ STR1 = ABCD $ TEST $ STR1 = ABCD $ ECHO $? The result shows: 0 is different from the equal number in the first row assignment statement in the previous example, and the equal number in the Test command must have spaces. This Test command has 3 parameters. Note that two strings must be equal to the length and content. $ Str1 = "abcd" $ test "$ str1" = ABCD $ Echo $? The result is displayed: 1 The str1 contains 5 characters, where the last one is a space. The other string in the Test command has only 4 characters, so the two strings are equal, TEST returns 1. Test a string result without any operator and using the -n operator, for example: $ str1 = Abce $ TEST $ STR1 $ Echo $? Result Show: 0 $ test -n $ str1 $ echo $? Results show: 0 However, there are also differences in the above two orders, reflecting the potential issues with Test commands, see below: $ str1 = "" $ TEST $ STR1 $ Echo $? Results Show: 1 $ TEST -N "$ STR1 "$ Echo $? Results show: 0 $ test -n $ str1 results display: Test: Argument Expected Previous example, the first test is false because the shell must first make a variable replace before executing the command line, ie $ STR1 It is spaced, and then shell deletes the space on the command line, so the test command is tested as an empty string. In the second test, the variable is replaced in parentheses, so it will not be deleted. Test test is a string containing spaces. In the third test, the shell deletes the space, only -N The Test command, so the parameter is displayed. 2> Test the relationship between the two integers The Test command is the same as the expr command, or the character can be converted into an integer and then operate it.
The TEST command is compared to the two numbers. The operator used is as follows: INT1 -EQ INT2 two numbers are true INT1-NE INT2 two numbers true int1 -gt INT2 INT1 greater than int2 is true INT1 -ge INT2 INT1 greater than equals INT2 is true INT1 -LT INT2 INT1 less than INT2 is true INT1 -LE INT2 INT1 less than or equal to INT2 as the true lower case reflects the comparison between the string and the digital comparison: $ STR1 = 1234 $ str2 = 01234 $ test $ str1 = $ STR2 $ ECHO $? results show: 1 $ TEST $ STR1-EQ $ STR2 $ Echo $? Results Show: 0 3> Tests for files Tests using TESTs are the status of test files, users can test if the file is Presence, whether it can be written and other file properties. Here is the options used when file testing. Note that only the file exists, it is likely to be true. -r file user can read as true -W file users can be written as true -x file users can execute as true -f file files for the true file for the true-D File file as the real-C file file as a character special file The true -B file file is a special file for the true-S File file size is true-bit file size is true -t file When a file descriptor (default is 1) specified device is true 4> Complex condition test (AND, OR, NOT) -A and -O or! Not a combination condition, any advanced language (not, and, or), for example: $ test -r em.null -a -s em.null $ echo $? Results show: 1 Description Em.null is not readable and non-empty file 5> Another method of performing Test's method BSH is another way to perform Test commands, is to put the test conditions in pair [], For example: $ int1 = 4 $ [$ INT1 -GT 2] $ Echo $? The result shows: 0 Be careful in the front of the [back and] symbols to have a space.
Below we use the test command to write a simple but relatively complete program: # - backup program # - Check the parameter if [$ # -ne 1] Then Echo "Please indicate the directory you want to back up by the program!" EXIT 1 Fi # - Check if the directory name is valid if [! -d "] THEN Echo" $ 1 is not a directory! "EXIT 2 FI CD $ 1 ls -a | cpio -o> / dev / mnT0 IF [$? -eq 0] THEN RM * ELSE Echo "CPIO execution is unsuccessful! Backup failed ..." EXIT 3 Fi 6> empty commands in BSH: represents an empty command, it is charged, nothing 7> Nested IF statement And ELIF Structure Check Condition 1 A: When the condition 1 is true, it is true that one of the operations B: If the condition 1 is fake, check conditions 2 1) If the condition 2 is true, another part of operation 2) If the condition 2 is fake, check Condition 3 3) If condition 3 is true, do other part of the operation syntax is as follows: if Command Ten Command Else if Command The Command Else if Command The Command FI FI FI 8> ELIF statement Nested IF statement sometimes brings confusion to the user, Especially when the Fi statement is difficult to judge. Therefore, the Bourne Shell provides an ELIF statement. Elif is an abbreviation of Else-if, it is indicated by the continuation of the IF statement. The format is: if Command The Command Elif Command The Nested IF statement and ELIF statements described above are used by the IF statement, and the user can choose one according to their own preferences. 9> CASE statement, the ELIF statement, replacing the IF-THEN-ELSE statement, but sometimes it will experience multiple times of the same variable during programming, which can be implemented with multiple ELIF statements, but there is another kind of Simple method is to use a CASE statement. The CASE statement not only replaces the plurality of ELIF and THEN statements, but also match multiple modes with variable values. After a mode is matched with the variable value, the following series of commands will be executed, below is used by the CASE statement Scriptures. Case Value In Pattem 1) Command Command ;; Pattem 2) Command Command ;; .... Pattem) Command; ESAC case statement onlys one of the sets of commands, only the first time when the variable value matches multiple modes, only the first The command corresponding to the matching mode is executed. ";;" indicates a command partial program corresponding to the mode. Through learning the following READ statement, let's give examples of the usage of the CASE statement. 10> Read statement shell program can not only get input data by command line parameters, but also use the read command to prompt the user to enter data, its syntax format is: read var1 var2 ... varn When the BSH encounters an READ statement, Read the data in a standard input file until a newline.
At this time, the shell does not perform the replacement of the file name or variable when explaining the input line, just simply deleting extra spaces. Then the shell gives the contents of the first word of the input line to the variable 1, the second gives the variable 2 until all variables are assigned or input behavior. If the number of words in the input line exceeds the number of variables, the shell will assign the content of all the words remaining in the input line to the last variable. When the number of variables is more than the number of input lines, more variables will assign an null value. Each word of the input row is a string that consists of a letter and a number separated by spaces. $ read var1 var2 var3 Enter: Hello My Friend $ Echo $ VAR1 $ VAR2 $ VAR3 Results Show: Hello My Friend $ Echo $ VAR2 Results Show: MY The following uses read and case's example ends this part of learning: # - interactive Backup, Recovery Procedure Echo "Enter the directory you want to back up file: / c" Read Workdir if [! -D $ workdir] Ten Echo "Sorry, $ WORKDIR IS NOT A DIRECTORY" EXIT 1 FI CD $ WORKDIR ECHO "input selection: "Echo _ echo" 1. Restore $ Workdir "Echo" 2. Backup $ Workdir "Echo" 0. Exit "Echo Echo" / C "Read Choice Case" $ Choice "in 1) Echo" Restore .... "CPIO -I dev / mnT0 ;; 2) Echo" Backup ... "LS | CPIO -O> / DEV / MNT0 ;; 0) EXIT 1 *) EXIT 1 ESAC IF [$ ? -ne 0] The echo "program running error!" Else Echo "Success!" Fi in the above code, "*" defines the default operation when mismatched in other mode. The procedures and the statements described earlier in the circulatory statement are from beginning to end into one main line, or the branch structure, during daily management Unix, often repeat some operations, processing bulk problems, this It involves the loop structure, similar to the high-level language, UNIX's shell also provides a powerful loop processing statement. There are three cyclic statements in the BSH language - the WHILE loop, the Until loop, and the For loop, the three structures are introduced separately by specific examples. The While loop is in the While cycle statement, when a certain condition is true, perform the specified command. The structure of the statement is as follows: While CommandDo Command Command ... DONE sample code as follows: # Test while loop applet x_t = 1 While [$ x_t -lt 5] do mm = `expr $ x_t / * $ int` # Note "/" Echo "$ mm" x_t = `expr $ x_t 1` # Note that the execution of Expr's usage done echo "The while is end! / N" program is as follows: 14916The while is end in the above program, when the variable X_t When the value is less than 5, the statement in the While loop is executed. When the fifth cycle, the [$ x_t-lt5] command returns a non-zero value, so the program executes the code behind DONE.
Now use the While loop, you can improve the example of the backup data used earlier. When the user specified by the directory backup, use the While loop to make the program perform a directory specified by multiple users. The code is as follows: echo "Welcome to the backup applet" ANS = y while [$ ANS = Y -O $ ANS = Y] do echo _ # read directory name echo "Enter the directory name to be backed up: / c" Read Dir IF [ ! -d $ dir] Then Echo "$ dir is not a directory!" EXIT 1 FI CD $ DIR Echo "Please select:" Echo _ echo "1 Restore Data to $ DIR" Echo "2 Backup $ DIR Data" Echo Echo "Please select: / c" Read Choice Case "$ Choice" in 1) Echo "Restore ..." CPIO -I 2) Echo "Backup ..." CPIO -O> / DEV / RMT0 ;; *) ECHO " Select Invalid "ESAC IF [$? -Ne 0] THEN Echo" CPIO execution process "EXIT 2 FI ECHO" continues other directory? (Y / Y) / c "Read Ans Done starts in the program, we give Variable ANS value is Y, according to the WHLIE judgment conditions, the program enters the While loop, execute the statement in do-done, each cycle requires the user to enter the value of the ANS to determine whether the next repeated execution Do-Done Scriptures. If the user entered the condition does not meet the While statement condition, the loop is over, the program executes the statement behind DONE. In the hantil statement, as long as a certain condition is true, repeat the loop code, the Until statement is in contrast to the While, the statement repeats the loop code until there is a certain condition. The structure of the Until statement is as follows: Until Command Do Command Command ... DONE can replace the While statement of the backup program above with the Until statement, complete the same function: Until [$ ANS! = Y -A $ ANS! = Y] for loop in the introduction Before the FOR loop, we have to learn a very useful unix command: Shift. We know that for position variables or command line parameters, the number must be determined, or when the shell program does not know the number, you can assign all parameters to the variable $ *. If the user requested shells to handle the parameters one by one by one of the number of position variables, it is $ 2 after $ 1, and it is $ 3 after $ 2. The value of $ 1 in the shift command is not available after the Shift command is executed.
Examples are as follows: # Test shift command (x_shift.sh) unshot command is: $ 1 parameter number: $ # "Shift Done Perform the above programs X_shift.sh: $. / X_shift.sh 1 2 3 4 Results As follows: The first parameter is: 1 parameter number: 2 The first parameter is: 2 The first parameter is: 3 parameter number: 1 The first parameter is: 4 Number of parameters is: 0 From the above, every time the shift command is executed once, the number of variables is reduced, and the variable value is advanced, the following code calculates all commands with the Until and Shift commands. The sum of the line parameters. #SHift's application (x_shift2.sh) IF [$ # -eq 0] Then echo "usage_shift2.sh parameter" exit 1 fi sum = 0 Until [$ # -eq 0] do sum = `expr $ SUM $ 1` Shift Done echo "SUM IS: $ SUM" Performs the above program: $ x_shift2.sh 10 20 15 Its display result is: 45 Shift commands There is another important purpose, BSH defines 9 position variables, from $ 1 to $ 9 This does not mean that the user can only use 9 parameters in the command line, and the shift command can access more than 9 parameters. The number of shift commands at a time of moving parameters is specified by the parameters they belong. For example, when the shell program handles the first nine command line parameters, you can use the Shift 9 command to move $ 10 to $ 1. After familiar with the Shift command, let's take a look at the BSH program very useful for loop statement, this loop is different from the While and Until loops above, whether the loop in the FOR statement is executed and does not help this to be true and That is to decide, determine whether the FOR cycle continues to continue is whether there is unprocessed parameters in the parameter table. The structure of the for statement is as follows: for variable in arg1 arg2 ... arggndo command Command ... DONE The following is a simple example of the for loop: for letter in ABC DDO Echo $ Letterdone program execution results are as follows: ABCD calculates the parameters and examples above, we You can use for loops to achieve the following: # Test the FOR program (X_for.sh) if [$ # -eq 0] Ten echo "usage_for.sh parameter ..." exit 1Fisum = 0for i in $ * do sum = `expr $ SUM $ I`doneecho "SUM IS: $ SUM" interrupt loop instructions In the program loop statement, we sometimes hope that the next loop will perform the next loop or end this loop when you encounter a middle situation. This involves two Statements: Continue and Break. The Continue command allows the program to ignore other instructions in the subsequent cyclic body, directly for the next loop, and the BREAK command ends the cycle, performs the statements behind the cyclic body.
# Test Continuei = 1WHILE [$ I -LT 10] DO if [$ I -EQ 3] Then Continue Fi IF [$ I-EQ 7] The Break Fi Echo "$ I / C" DONE performs the above program, the result is as follows: 12456789 Multi-different methods can be used in a variety of different ways to complete the same functionality, such as Until and While statements, using multiple different methods, using multiple different methods, such as Until and While statements, in addition to the IF-THEN-ELSE structure You can make the above functions outside of the commands that can be made. These two operators represent logic and logic or operations in the C language. In the Bourne Shell, the meaning of the two commands with && connection is only successfully executed, and the commands will be executed. && operations are: Command && Command, such as statement: RM $ TEMPDIR / * && Echo "files successfully removed" only the echo command will only be executed after the RM command is successfully executed. If the above function is implemented by the IF-THEN statement, the form is: if rm $ TEMPDIR / * THEN Echo "Files SuccessFully Removed" Fi, with || Connecting two commands The meaning of only the first command to perform failure to execute the second Articles, for example: RM $ TEMPDIR / * || Echo "File Were Not Removed" The equivalence of the above statement is: IF RM $ TEMPDIR / * THEN: ELSE Echo "Files Were Not Removed" Fi These two operators can Joint use, as in the command line below, only Command1 and Command2 are successful, Command3 will execute: Command1 && Command2 && Command3 The following command line indicates that Command2 is not executed successfully, and Command2 will not perform Command3. && and || Operators can simplify the format performed by the command condition, but generally only perform the condition of one command. If many commands use these two operators, the readability of the entire program will become very poor, so it is best to use a readable if statement when performing the condition of multiple commands. Function Now we introduce the function section in the shell program. Basically any advanced language supports the function. It can make us more than a lot of things, at least the same thing, the same thing, good function in the com otherwll program The function is called a subroutine, which can be called anywhere in the program, and its format is as follows: Function Name () {Command ... Command;} The SHELL program can be called with the command "function name", There are two advantages to the use of functions, one is to use a function to make a complex program into multiple modules, easy to manage, comply with the design idea of structured procedures, and another benefit is the reuse of the code. The shell function and the shel program are similar, and their difference is that the shell program is run in the sub-shell, while the shell function runs in the current shell. Therefore, you can see the modification of the variable in the current shell.
Functions can be defined in any shell, including interactive shells. For example: $ dir () {ls -l;} The result is that we play DIR behind $, and its display results are the same as LS -L's role. The DIR function will always reserve the user from the system exit, or execute the unset command as shown below: $ unset dir Next example illustrates the function can also accept location parameters: $ dir () {_> echo "Permission ln Owner Group File Sz Last Access> LS -L $ *;>} Run DIR A * to see what results parameter a * is passed to the DIR function and replaced $ * usually the shell program will be executed in the sub-shell, the program changes the variable It is only valid in the child shell and is invalid in the current shell. "." The command can make the shell program in the current shell. The user can define a function in the current shell and assign the variable. Usually re-initially with the following command. PROFILE Settings to the Shell environment. $ .profile Since this is relatively simple, we are in the way that Trap is good to use the trap command to perform exceptions to handle some exceptions when the program is running, such as executing it. The user presses the interrupt button or use the kill command, or the control terminal is suddenly disconnected by the system. The above case in theunix system will send the system to the process, usually the signal is turned to the process. Sometimes the user wants to hope The process performs some special operations when receiving the termination signal. If the process generates some temporary files during runtime, the temporary file generated by the process will be retained. In BSH, the user can use The TRAP command modifies the default operation when the process receives the termination signal. The TRAP command format is as follows: Trap command_string Signals A total of 15 signals issued to the process, by default, most of the signals will end the program. User is best to check yourself The system's textbook, see the type of signal used in the system. In addition to the signal 9 (the real KILL signal) cannot use the trap command, the operations of other signals can be specified in the TRAP command. The following is the trap command Several signals often used: Signal function 1 Suspend 2 Operation Interrupt 15 Soft Termination (Kill Signal) If the command string contains not only one command, you must use the quotation to enclose the entire command, specifically single quotes or double quotes, by The user needs a variable replacement decision. "" Replace, '' does not replace. Use the following trap command to make the program when receiving hang, interrupt, or kill signal, first Time file deletion, then exit: Trap "RM $ TEMPDIR / * $; EXIT" 1 2 15 In the above example, when the shell reads the trap command, first change the $ TEMPDIR and $$, replace the command after replacement The string will be saved in the TRAP table. If the trap command is used in the above example, the trap command is not performed, and the command string RM $ TEMPDIR / * $$; EXIT is placed in the trap table, When the signal is detected, the program explains the command string in the TRAP table, and the variable replacement is performed. The value of the previous variable $ Tempdir and $$ is the value of the TRAP directive, and the value of the variable in the latter case is the value of the program to receive the signal, so ", 'must distinguish carefully.
The meaning of the following command is after the secondary interrupt key, the program is terminated: Trap 'TRAP 2' 2 The command string in the TRAP command contains almost all of the EXIT statement, and the example of the above RM does not have an exit statement, receive signal RM The command execution will hang. However, sometimes the user also needs to hang after receiving the signal, for example, when the terminal and system are disconnected, the user issues a suspend signal, and performs an empty command, as follows: TRAP: 1 If the user wants to cancel the command string set before the TRAP instruction set The trap command can be executed, and the command string is not specified in the command indicates that the default operation is performed after receiving the signal. The command is as follows: Trap 1 Specifies shell Get the Unix type Option: Unix has an advantage is that the standard UNIX command is executed. The same command line format: Command -Options Parameters If the SHELL program is executed, a statement that gets and processes the command line option is provided in the Bourne Shell, which is a getOPTS statement. The format of this statement is: getopts option_string variable where Option_String contains a valid single character option. If the getOpts command discovers the hyphens in the command line, it will compare the characters behind the hyphen to Option_String. If there is a match, set the value of the variable Variable to this option. If there is no match, Variable is set to? When the getopts finds that there is no character behind the character, a non-zero status value is returned. A loop can be established using the return value of GetOpts in the shell program. The following code illustrates how to use the getopts command in the Date command to process various options, which adds many new options in addition to completing the function of UNIX standard command Date. # 新 新 程序 i [t 新 t t m;; t t;;;;;;;;;; Y ';; D) Date' % D ';; h0date' % h ';; m) Date' % M ';; S) Date' % S ';; T) Date' % T ' ; J) Date ' % J' ;; J) Date ' % Y% J' ;; W) Date ' % W' ;; a) Date ' % a' ;; h) Date ' % H ';; R) Date' % R '; /?) Echo "Invalid Options! $ Option" ;; ESAC Done Fi Sometimes a value is also taken, the getOpts command also supports this feature. At this time, you need to add a colon after the letters in Option_String. When the getOpts command finds the colon, the value will be read from the command line. If this value exists, there will be a special variable OPTARG. If this value does not exist, the getOpts command stores a question mark in the Optarg and displays a message on the standard error output. The following example is implemented to copy a file and assign a new name to the file.
-c Option Specifies the number of program copies, the -v option requires the file name of the newly created file. # - Copy Program COPIES = 1 Verbose = N While Getopts VC: OPTION Do Case $ OPTION IN C) COPIES = $ OPTARG ;; V) Verbose = Y ;; /?) Echo "Invalid Parameters!" EXIT 1 ;; ESAC DONE IF [$ OPTIND -GT $ #] The echo "no file name specified" EXIT 2 FI Shift 'expr $ optind - 1' file = $ 1 copy = 0 while [$ copies -gt $ copy] do copy = 'expr $ Copy 1 'cp $ file $ {file} $ {copy} if [verbose = y} the echo $ {file} $ {copy} Fi Done
Specifications Shell: We know that the environment variable PS1 is a prompt, look at the program chDIR: if [! -D "$!"] Then Echo "$ 1 is not a directory" EXIT 1 FI CD $ 1 PS1 = "'PWD'>" Export PS1 We do: $ chDIR / USR / ICE666 results prompt symbol becomes / usr / ice666>? No, why? The reason is that chDIR is executed in the sub-shell, and the modification of the variable PS1 does not work in the current shell. To complete the imperial function, the command must be executed in the current shell. The best way is to change it into a function and define it in .profile file. However, if you want to put the function in a single file and execute in the current shell, you need to use. Command, and rewrite CHDIR into a function, turn the exit to Return. The following code is .ice_ps content: # - prompt chdir () {if [! -D "$ 1"] THEN Echo "$ 1 is not a directory" Return Fi CD $ 1 PS1 = "'PWD'>" Export PS1; } Then we join the following statement in the .profile file. Iice_PS then when switching the directory, we use the chdir command, what is the result, you have a good experiment! Debug the shell program 1> Debug shell program users just write the shell program It will inevitably there will be errors, then we can use the tracking options provided in BSH, which displays the commands and parameters that have just been executed. Users can open the -X option via the set command or set the shell into tracking mode with the -X option in the startup. For example, there is a code ICE_TX: IF [$ # -eq 0] the echo "usage: Sumints Integer List" exit 1 fi sum = 0 Until [$ # -eq 0] do sum = 'expr $ SUM $ 1' Shift Done Echo $ SUM We use tracking mode: $ SH -X ICE_TX 2 3 4 results show: [3-EQ 0] SUM = 0 [3-EQ 0] EXPR 0 2 SUM = 2 Shift [ 2-EQ 0] EXPR 2 3 SUM = 5 Shift [1-EQ 0] EXPR 5 4 SUM = 9 [0-EQ 0] Echo 9 9 It can be seen from above, track Each command executed in the mode and the variable used by the command replace the parameter value after the change is used. Some control words are not displayed if IF, THEN, and Unsil, etc. 2> Command Group The number of commands can form a unit together. In order to identify a set of commands, these commands must be placed "()" or "{}". The command placed in "()" will run in the sub-shell, and the command placed in "{}" will run in the current shell. The command running in the child shell does not affect the current shell variable. The command running in the current shell affects the current shell variable.
$ Number = 2 $ (a = 2; b = 2; Number = 'expr $ A $ b'; echo $ number) Result: 4 $ Echo $ Number results: 2 If the above () becomes {} What is the result? 3> Using the Shell Timer Manager SHL UNIX is a multi-programming operating system, some UNIX systems provide the Shell Hierarchy Manager SHL using this feature. Use SHL users to open multiple hierarchical shells at a time, where the active shell can get input from the terminal. However, all SHELL outputs can be displayed on the terminal unless disabled. There is a SHL in multiple shells, and when the user operates in a shell, it can return to SHL using a special character (typically Ctrl Z). In order to distinguish other shell, the prompt in SHL is ">>>". When the user works in the Shell Hierarchy Manager, you can create, activate, and delete the shell, below is the command used in SHL. Create Name Generates Level DELETE NAME DELETE NAME DELETE NAME The hierarchy of the Name Block Name is forbidden to name the Name of the Name, the unblock name recovered the hierarchy of the Name, the resume activation named Name hierarchical Toggle Activation Recently used Level Name Activation Name Layers [-l] name to each level in the table displays the process number of its running process, and the -l option requires displaying details. Help Shows SHL Command Help Information Quit Exit SHL and all activated hierarchical summary in front of us mainly introduced the variable of SH, basic syntax, program design, etc. If you master these content, when learning other UNIX programming languages, I believe there must be some benefits. We said, there are Bourn shells in most UNIX, and there are very few pictograms like SH. It is a wealth of system administrators and programmers, and does not require additional software environments, dealing with files, and implementation than C implementation is simpler than C.