Bourne shell and shell programming

xiaoxiao2021-03-06  40

Copyright Notice:

This article is the Linux elective course of Dalian University of Technology. You are welcome to reprint, but it is forbidden to use this material.

Any commercial or profitable event. Please keep this copyright statement when you reprint.

Author: He Binwu, hbwork @ dlut.edu.cn, Network Center of Dalian University of Technology, April 1999.

URL:

ftp://ftp.dlut.edu.cn/pub/people/Albin/

Bourne Shell Introduction: Bourne Shell Basics and many other useful features, shell programming and organization. Main contents:. SHELL basic introduction, environment, option, special character. SHELL variable user defines variables, environment variables, position variables (shell parameters). SHELL Script programming condition test, loop and repeat control. SHELL customizable 1.shell basics author: Stephen Bourne at Bell labs developed recommendations: man sh see improvements or characteristic (1) shell prompt and environmental / etc / passwd file prompt on the associated UNIX: $ / etc / profile $ HOME / .profile (2 SHELL execution option-N Test the Shell Script syntax structure, only the shell script but does not perform the -X to enter the tracking mode, display each command executed, used to scheduling -a tag all variables for export -c "string" from Strings Read Command-E Non-interactive mode -f Close Shell File Name Generating Function - H Locate and Remember Functions AS DEFIND -I Interactive WTRY - K From the Environment Variable Parameter -R Limit Handle-S-S After reading the command -T execution command After the SHELL EXITS) -U is used to use undefined variables to be error -V Verbose, display shell input row can be used in combination, but some obviously conflicts with each other, such as -e and i. (3) Restricted Shell (RESTIRCTED Shell) SH -R or / BIN / RSH cannot perform the following operations: CD, change PATH, specify full path name, output redirection, so you can provide a better control and security mechanism . Typically RSH is used for application-type users and dialing users, which are usually noteworthy. The main directory of usually restricted users is not writable. Insufficient: If the user can call SH, the RSH limit will not work, in fact, if the user calls the shell in the VI and MORE programs, the limit of RSH will no longer work. (4) Change the shell option with SET Change The user can set or cancel the shell option with the set command at the prompt. Using - Settings Options, Cancel the appropriate option, most UNIX systems allow Switch setting / cancellation of A, E, F, H, K, N, U, V, and X. SET -XV start tracking mode; display all commands and replacement, also display input. Set -TU turns off check for undefined variables during replacement. Use echo $ - Show all set shell options.

(5) User start file .profile path = $ path: / usr / loacl / bin; Export Path (6) shell Environment Variable CDPath Used for CD Commands User Home / etc / Passwd files listed in Home / etc / passwd file IFS Internal Field Separator, default is space, Tab, and PNAME MAIL / VAR / MAIL / $ Username Mail and other programs use Path PS1, PS2 default prompt ($) and wrap prompt (>) Term terminal type, commonly used VT100, ANSI, VT200, XTERM, etc. Example: $ PS1 = "Test:"; Export PS1 Test: PS1 = "/ $"; Export PS1 $ Echo $ Mail / Var / Mail / UserName (7) Reserved Character and Its Inelling $ SHELL Variable The beginning of the name, such as $ VAR | pipeline, transfer the standard output to the next command to the next command # 注释 开始 & In the background execution? Match a character * Match 0 to multiple characters (Unlike DOS, you can use it in the middle of the file name, and.) $ - Take the SELL in the SET and execution to the SHELL $! The last child process number $ # Passage to Shell Script Number of parameters $ * Pass to Shell Script $ @ All parameters, individual use double quotes $ 0 Return to code $ 0 Current Shell's name $ n (N: 1-) Location Parameters $$ Process Identifier Number, PID> File Output Redirects > Fiile output redirector, Append escale and single quotes: $ echo "$ home $ path" / home / hbwork / opt / kde / bin: / usr / local / bin: / bin: / usr / bin: $ Echo '$ Home $ PATH' $ Home $ Path $ Echo / $ Home $ HOME / OPT / KDE / BIN: / USR / local / bin: / bin: / usr / bin: / usr / x11r6 / bin: / Home / HBW ORK / BIN Other: $ DIR = LS $$ Dir $ Alias ​​Dir LS $ DIR LS> FileList LS >> FileList Wc -l

LS -L PS AX | EGREP inetd Find / -Name Core -Exec RM {} /; & filename = `Date" % Y% M% D "` .log 2. Shell Variable Variable: Represents Some values ​​symbol, For example, the cd command looks for $ HOME, you can use variables in your computer language to make multiple operations and control. Bourne Shell has the following four variables: user-defined variables. The location variable is the parameter of the shell script. Pre-defined variable (special variable). Environment variable (reference shell custom section) (1) User-defined variable (data storage) $ Count = 1 $ name = "He Binwu" Tips: Because most UNIX commands use lowercase characters, usually use all current write variables in Shell program, of course, this is not mandatory, but use uppercase characters can be convenient in programming The variable is identified. Variables Call: Adding $ $ $ HOME / HOME / HOME / IS $ Week = Satur $ Echo Today IS $ = SATUR $ Echo Today IS $ {Week} Day Today Is Saturday Shell Variable assignment from left to left Linux Shell / Bash assigns a value from left to right!) $ X = $ y Y $ c $ x y $ z = z y = $ z $ = $ y $ usage UNET command Delete Variables $ z = Hello $ Echo $ Z Hello $ Unset Z $ Echo $ z $ Conditional command Replace the variable to replace the variable in a specific condition, that is, the conditional environment variable is replaced. This variable replacement is always enclosed in braces. The default value for setting variables is empty before the variable is not assigned.

Bourne Shell allows the default value to the variable, its format is as follows: $ {variable: -defaultvalue}: $ echo hello $ uname Hello $ Echo Hello $ {uname: -there} Hello the $ Echo $ uname # variable value does not occur Change $ uname = HBWORK $ Echo Hello $ {uname: -there} Hello HBwork $. Another situation: Variable variables, formats are as follows: $ {variable: = value}: $ Echo Hello $ uname Hello $ Echo Hello $ {Uname: = there} Hello The $ echo $ uname # variable value does not change the are $. Variable replacement Use the command to replace $ userDIR = $ {$ mydir: -`pwd`}. Replace when the variable has assigned $ {variable: value}. There is a conditional variable with an error check $ {variable:? Value}: $ uname = $ echo $ {uname:? "" uname "} uname: uname: uname Has Not Been Set $ ​​echo $ {uname :?} uname: Parameter Null or Not Set (2) Location Variable (Shell Parameters) The location parameters in Shell Script can be used for $ 1. $ 9, $ 0 means that the content is usually the file name of the current execution program. Prevent variables from replacing readOrthly variable. Use the export command to output the variable, so that the variable pair of sub-shells, when the shell performs a program, the shell will set a new environment to make it execute, this is called Subshell. In Bourne The variables in the shell are often considered to be local variables, which means that this variable is not recognized outside the shell environment other than its assignment. Use Export to Subshell. Example: The export operation of the variable PS1, the shell's prompt will change.

$ Ps1 = `Hostname` $ PEONY $ SH $ ps1 $ <- Output $ EXIT Peony $ ECHO $ ​​PS1 Peony $ Sh PEONY $ Echo $ PS1 Peony $ - Output PEONY $ 3.SHELL Script Programming Purpose: Using Unix The most common tools provided to accomplish the powerful function of the required complex tasks. (1) The simplest shell program $ ls -r / | grep myname | More data for daily data: $ CD / USR / YOURNAME; LS * | CPIO -O> / dev / RMT / 0H Write program is a programming Use multiple times (execution)! $ cat> backup.sh cd / home / hbwork ls * | cpio -o> / dev / rmt / 0h ^ D Execution: $ sh backup.sh or: $ chmod x backup.sh $ ./backup.sh tip: Add the necessary annotations in Shell Script for future reading and maintenance. (2) Shell is a (programming) language, like a traditional programming language, Shell provides a lot of features that make your shell Script programming more useful, such as data variables, parameter delivery, judgment, process control, data Input and output, subroutines, and interrupt processing, etc.

Using data variables in Shell Programming can make program variables more common, such as backup.sh above: CD $ Workdir ls * | CPIO -O> / dev / rmt / 0h. Shell programming in # 开头. Digital operations for the shell variable, using the expr integer Operator Integer where Operator is - * /%, but the * is used to use esters /, such as $ expr 4 / * 5 20 $ int = `EXPR 5 7` $ ECHO $ ​​INT 12 (3) SHELL programming parameter passes, can restore $ cat> restoRL.SH CD for backup tapes of Backup.SH programs by command line arguments and interactive input variables (Read) RESTOREALL.SH $ WORKDIR CPIO -I / dev / rmt / 0h rm -rf * Improvements as follows: # When using the pipeline command, the return code of the management command is the return code for the last command IF ls -a | cpio -o>

/ dev / rmt / 0H THEN RM-RF * Fi. if-kil_1 statement if common_1 THEN COMMAND_2 ELSE COMMAND_3 FI TTS: Since the shell is not handled by the unnecessary spaces in the command, a good programmer will use this Features use unified indentation formats to enhance their own program to enhance the readability of their own programs. Conditional test format using the test command: Test Conditions Test Use: a. Character comparison B. Two Comparison of integer values ​​C. File operation, such as files existent and file status, etc. D. logic operation, you can perform and / or use a. Test character data in combination with other conditions: SHELL variables Under the Ministry of Civil Affairs as a character variable STR1 = STR2 is too long, the same STR1! = STR2 Different String String is not empty (length is not zero) -z string string is empty String String String String String String String String: $ str1 = Abcd # must be used in space Quotes enclose $ TEST $ STR1 = Abcd $ Echo $? 0 $ str1 = "abcd" $ TEST $ STR1 = Abcd $ Echo $? 1 Note: It is best to use the quotation to enclose the variable when TEST processing variables containing spaces. Otherwise, there will be a result of errors because shell is processed. The excess space will be removed when the command line is used, and it can prevent Shell from removing these spaces. Example: $ str1 = "" $ TEST $ STR1 $ Echo $? 1 $ TEST "$ str1" $ Echo $? 0 $ TEST-N $ STR1 TEST: ARGUMENT EXPECTED $ TEST-N "$ STR1"

$ Echo $? 0 $ b. Integer Test: TEST is the same as EXPR, you can convert the character variable to an integer, and EXPR is integrated arithmetic operation, while TEST performs logical operation. Expression description ------ ------------------------------- INT1-EQ INT2 equal? ​​INT1-Ne INT2? INT1 -GT INT2 INT1> INT2? INT1 -GE INT2 INT1> = INT2? INT1 -LT INT2 INT1 EMPTY $ TEST -R EMPTY $ Echo $? 0 $ TEST -S EMPTY 1 $ TEST! -S EMPTY $ Echo $? 0 E. Test Conditions Logic - A and -O OR: $ TEST -R EMPTY -A -S EMPTY $ Echo $ ECHO $ ? 1 f. Standard method for test testing because the test command possesses a very important position in Shell program, in order to make the shell to read and organize the same for other programming languages, Bourne Shell uses another method when using TEST testing. : Use square brackets to collapse the entire TEST: $ INT1 =

4 $ [$ INT1 -GT 2] $ Echo $? 0 Case: Rewote the unload program, use TEST test #! / Bin / sh #unload - Program to backup and remove Files #Syntax: unload Directory #Check Arguments IF [$ # --ne 1] THEN Echo "USAGE: $ 0 DIRECTORY" EXIT 1 Fi #Check for Valid Directory Name if [! -d "$ 1"] THEN Echo "$ 1 is not a directory" EXIT 2 FI CD $ 1 LS -A | CPIO -o> / dev / rmt / 0H IF [$? -eq 0] THEN RM-RF * ELSE Echo "A Problem Has Occured In Creating Backup" Echo "The Directory Will Not Be EREASED" Echo "Please check the backup device" EXIT 3 FI # End of Unload appears in the example, exit has two functions: First, the execution of other commands in the stop program, the second is the setup status g. if nested and ELIF structure IF Command THEN Command Else if Command The Command Else if Command Then Command Fi Fi Fi Improvement: Using the Elif structure if Command The Command Elif Command The Command Elif Command The Command Fi Elif structure is similar to the IF structure, but the structure is clearer, its execution result is complete The same .bourne shell and shell programming (2) h. Interactive reading data from the keyboard to use the READ statement, its format is as follows:

Read var1 var2 ... Varn READ will not be variable replace, but the extra space will be deleted until the first wrap (Enter) is encountered, and the input value is assigned to the corresponding variable.

Example: $ Read Var1 Var2 Var3 Hello My Friends $ Echo $ VAR1 $ VAR2 $ VAR3 HELLO My Friends $ Echo $ VAR1 HELLO $ Read Var1 Var2 Var3 Hello My Dear Friends $ Echo $ VAR3 Dear Friends <- Enter the value when entering excess variables The remaining content gives the last variable $ read var1 var2 var3 hello friends $ Echo $ VAR3 <- VAR3 is empty $ Echo in Shell Script Using the READ statement to interact: ... #echo -n message output after the output echo -n "do you want to contact: y or n" Read Answer IF [$ answer = N -O $ answer = n] The EXIT FI I. CASE Structure: The structure is more clear comparison if the Elif-Then structure is more clear compared to the IF-THEN statement : IF [variable1 = Value1] Then Command Command Elif [Variable1 = Value2] Then Command Command Elif [Variable1 = Value3] THEN COMMAND Command Fi Corresponding Case Structure: Case Value In Pattern1) Command Command ;; Pattern2) Command Command ;; ... Pattern - Command; ESAC * CASE statement only performs the first match mode: Use the CASE statement to create a menu Select Shell Script #display a menu Echo _ echo "1 Restore" Echo "2 Backup" Echo "3 unload" echo #read and excute the user's selection echo -n "Enter Choice:" Read Choice Case "$ Choice" in 1) Echo "restore" ;;

2) Echo "backup" ;; 3) Echo "unload" ;; *) Echo "Sorry $ choice is not a valid choice exit 1 ESAC in the previous example, * refers to the default matching action. In addition, Case mode can also be used Logic operations as follows: pattern1 | pattern2) Command Command ;; This can allow the above sample program to allow users to enter numbers or every uppercase letter.

Case "$ Choice" in 1 | R) Echo "rest" ;; 2 | b) echo "backup" ;; 3 | u) echo "unload" ;; *) echo "sorry $ choice is not a valid kice exit 1 ESAC (5) loop control <1> while loop: Format: while command do command Command Command ... DONE Example: Calculating 1 to 5 square #! / bin / sh # #filename: Square.sh int = 1 while [ $ int -le 5] do sq = `expr $ int / * $ int` Echo $ sq Int =` expr $ int 1` Done Echo "Job Completed" $ Sh Square.sh 1 4 9 16 25 Job Completed <2 > Until loop structure: Format: Until Command Do Command Command .... Command Done Example: Using the Until Structure Calculation 1-5 Square #! / bin / sh = 1 Until [$ INT -GT 5] Do Sq = `expr $ int / * $ Int` Echo $ SQ INT = `EXPR $ INT 1` DONE Echo" Job Completed "<3> Using Shift to handle unordered parameters in the above example we always assume that the command line argument is unique or a number of fixed numbers, or use $ * Pass the entire command line parameter to the Shell Script for processing. The number of parameters is not fixed and it is desirable to handle each command parameter separately.

With Shift, you can move the command line location parameters, $ 2 -> $ 1, $ 3 -> $ 2. The first position parameter before shift is not existing after shift. Examples are as follows: #! / Bin / sh # #filename: Shifter Until [$ # -eq 0] do echo "argument is $ 1 and` expr $ # - 1 `Argument (s) Remain" Shift Done $ Shifter 1 2 3 4 Argument IS 1 and 3 Argument (s) Remain Argument IS 2 and 2 Argument (s) Remain Argument IS 3 and 1 argument (s) Remain Argument is 4 and 0 argument (s) Remain $ Using Shift, each shift $ # Minus 1, using this feature can be processed using the Until loop to process each parameter, as in the following example is a shell script: #! / Bin / sh # Sumints - a Program to Sum a Series of Integers # IF [$ # -eq 0] Then Echo "Usage: Sumints Integer List" EXIT 1 Fi Sum = 0 Until [$ # -eq 0] Do Sum = `EXPR $ SUM $ 1` Shift Done Echo $ SUM $ SUMINTS 324 34 34 12 34 438 What is another reason for using Shift is the location parameter variable of Bourne Shell is $ 1 ~ $ 9 Therefore, only the first 9 parameters can only be accessed by position variables. But this is not equal to the maximum number of 9 parameters on the command line.

At this time, if you want to access the parameters after the first nine parameters, you must use Shift. In addition, you can add a plurality of shifts, such as Shift 3 <4>. For loop format: for var in arg1 arg2 .. Sample of the Argn Do Command .... Command Done example: $ for letter in abcde; do echo $ letter; done abcde Actions to all files in the current directory: $ for i in * do if [-f $ i] TEN ECHO " $ I is a file "Elif [-d $ I] echo" $ I is a directory "Fi Done Que to line all integers: #! / bin / sh amount = 0 for int in $ * do sum =` Expr $ SUM $ INT` DONE Echo $ SUM <6> Exit from the loop: BREAK and Continue Commands Break immediately exits the loop Continue ignores the other commands in this loop, continue the next loop in the shell programming sometimes us To use the skill of the infinite loop, that is, this loop has always performed touching the BREAK or Continue command. This infinite loop is usually starting using the True or false command. TRUE in the UNIX system always returns 0 values, and False returns a non-zero value.

As shown below: # Opening to the program to end the Break or user forcibly interruption, end the loop whiling While True Do Command .... Command Done can also use the loop shown in the above, as follows: unsil false do command ... COMMAND DONE uses regular expressions in Continue, Break, and CASE statements in the following shell script: #! / bin / sh # interactive program to restore, backup, or unload # a Directory Echo "Welcome to the menu Driven Archive program "while true do # Display a Menu echo echo" Make a Choice from the Menu below "echo _ echo" 1 Restore Archive "echo" 2 Backup directory "echo" 3 Unload directory "echo" 4 Quit "echo # Read the User's Selection Echo -n "Enter Choice:" Read Choice Case $ Choice In [ 1-3]) Echo # read and validate The name of the directory echo -n "What Directory Do You Want?" Read Workdir if [! -D "$ workdir"] Then Echo "Sorry, $ Workdir is not a directory" Continue Fi # make the Directory THE CURRENT WORKING DIRECTORY CD $ WORKDIR ;; 4): ;; #: is empty statement, do not perform any action *) Echo "Sorry, $ Choice is not a valid choice"

Continue Esac Case "$ Choice" in 1) Echo "Restoring ..." CPIO -I / DEV / RMT / 0H ;; Echo "unloading ..." LS | CPIO -O> / DEV / RMT / 0H ;; 4) Echo "quitting" Break ;; esac #Check for cpio errors if [$? -Ne 0] THEN Echo "A problem HAS Occurred During The Process" IF [$ Choice = 3] Then Echo "The Directory Will NOT BE ERASED" FI Echo "please check the device and try again" Continue Else IF [$ choice = 3] THEN RM * FI Fi Done (6) Structured Programming: Define functions are the same as other advanced languages, and the shell also provides functional functions. The function is also called subroutine, and its definition format is as follows: funcname () {Command ... command; # 号} Defines a function, you can call this function in the shell and use function definitions. A complex program is divided into multiple manageable blocks as follows: # start program setup () {command list;} do_data () {Command List;} cleanup () {Command List;} errors () {Command List;} setup do_data cleanup # End Program Tips: It is best to use a meaningful name when named function, that is, the function name is more accurate description of the task completed.

For the maintenance of the program, use another advantage of using a comment as much as possible to perform the same command sequence (function) can be performed in different places in a program, as follows: iscontinue () {while true do echo -n "Continue? (Y / N)" Read Answer Case $ ANSWER IN [YY]) RETURN 0 ;; [NN]) Return 1 ;; *) Echo "Answer Y OR N"; ESAC Done} This can be programmed in Shell Middle-calling iscontinue to determine if the ISCONTINUE THEN Continue Else Break Fi ** shell function is very similar to the shell program, but both have a very important difference: the shell program is executed by the sub-sh ELL, and the shell function is as Some of the current shell is executed, so the definition of the function can be changed in the current shell.

In addition, in any shell (including interactive shell), a definitionable function, such as $ dir: NOT FOUND $ dir () {ls -l;} $ dir total 5875 -rw-r - r - 1 HBwork 100 NOV 10 23:16 DOC -RW-R - R - 1 HBwork 2973806 NOV 10 23:47 NS40DOCS.ZIP -RW-R - R - 1 hbwork 1715011 NOV 10 23:30 ns840usr.pdf -rw- R - r - 1 HBwork 1273409 Sep 23 1998 Radsol21b6.tar.z -RW-R - R - R - 1 HBwork 7526 NOV 10 23:47 wget-log -rw-r - r - 1 HBwork 1748 NOV 13 21:51 Wget-Log.1 $ unset Dir $ dir () {> echo "Permission Link Owner Group File_sz Lastaccess FileName"> Echo "------------------- -------------------------------------------- "> ls -l $ *; $ DIR Permission Link Owner Group File_Sz Lastaccess FileName ------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ Total 5875 -RW-R - R - 1 HBWORK 100 NOV 10 23:16 DOC -RW-R - R - 1 HBwork 2973806 NOV 10 23:47 NS40DOCS.ZIP -rw-r - r - r - 1 HBwork 1715011 NOV 10 23:30 NS840USR.PDF -RW-R - R - 1 HBWORK 1273409 SEP 23 1998 Radsol21b6.tar.z -RW-R - R - 1 HBwork 7526 NOV 10 23:47 wget-log -rw-r - r - 1 HBwork 1748 NOV 13 21:51 Wget-Log.1 Usually, shell script is executed in the sub-shell, which is here The modification of the variable in the child shell does not work on the parent shell. The point (.) Command uses the shell to read and execute a shell script by the current shell without creating the child shell, which can define functions and variables in this way. This (.) The most commonly used function is to reconfigure the initialization login variable by reading .profile. As shown below: $ ..profile (CSH is relative to. Command is a source command). (7) Use the AND / OR structure to perform conditional commands <1> and, only when the first command is successful The latter command is as necessary to continue when logical and expression is true, otherwise it is definitely false.

The format is as follows: Command1 && Command2: RM $ TEMPDIR / * && Echo "File successfully removed" equivalent to IF RM $ TEMPDIR / * THEN Echo "File SuccessFully Removed" FI <2> OR, opposite to And, only current command After performing an error, the last command is performed: RM $ TEMPDIR / * || Echo "File Not Removed" Equivalent with: IF RM $ TEMPDIR / * THEN COMMAND ELSE Echo "File Not Removed" Fi <3> Mixed Command Conditions Command1 && Command2 && Command3 When Command1, Command2 is successfully executed when Command1 && command2 || comamnd3 is only successful when Command1 is successful, and Command2 can only perform a combination of multiple conditional commands according to their own needs, not much to tell .

(8) Read the Unix Format Options Unix Format Options Unix Format Options Near the format: Command -Options Parameters use the format: getopts option_string variable Specific use method Please refer to Getopts' online document (man getopts). Example: # NewDate IF [$ # -lt 1] Then Date Else While Getopts MDYDHMSTJJWAHR OPTION DO CASE $ OPTION IN M) DATE ' % M' ;; # month of year d) Date ' % d'; # day of month y Date ' % y' ;; # year d) Date ' % d' ;; # mm / dd / yy h) Date ' % h' ;; # Hour M) Date ' % M' ;; # Minute s) date ' % s' ;; # second T) Date' % T ';; # hh: mm: ss j) Date' % J ';; # day of year j) Date' % y % J ';; # 5 Digit Julian Date W) Date' % W ';; # day of the week a) Date' % a ';; # day abbreviation h) Date ' % h' ;; # month abbreviation r) Date ' % r' ;; # AM-PM Time /?) Echo "Invalid Option $ Option" ;; ESAC Done Fi $ newdate -j 94031 $ newdate -a - H -D MON JAN 31 $ NewDate -ahd Mon Jan 31 $ sample program:

Copy the program # syntax: duplicate [-c integer] [-v] filename # where integer is the number of duplicate copies # and -v is the verbose option copies = 1 verbose = N while getopts VC: Option do case $ OPTION IN C ) COPIES = $ OPTARG ;; V) verbose = y ;; /?) Echo "Illegal option" 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] TEN Echo $ {File} $ {copy} Fi Done $ duplicate -v filea filea1 $ duplicate -c 3 -v fileb fileb1 fil EB2 FILEB3 4. The customization of Shell usually uses the shell customization to control the user's own environment, such as changing the shell's appearance (prompt) and enhancing your own commands. (1) Usually the environment variable is customized to change the environment variables to customize the working environment. When the shell is processed, refer to these environment variables, changing the value of the environment variable to a certain extent, such as changing the command line prompt. To add the IFS to the default state of the command line separator is a space, a tab, and a newline, but can be added to the own separator by changing the value of the IFS.

As shown below: $ IFS = ":" $ echo: hello: my: friend hello my friends (2) Add your own commands and functions as follows: #directory and prompt change program #syntax: chdir directory if [! -D " $ 1 "] THEN Echo" $ 1 IS NOT A DIRECTORY "EXIT 1 FI CD $ 1 PS1 =` PWD` $ export ps1 $ chDIR / USR / HOME / TERESA $ But this program does not change when execution, because this The program is executed in the sub-shell. Therefore, its variable has no effect on the current shell. To work on the current shell, it is best to write this as a function in its own .profile or build its own personal function file .Persfuncs #personal function file personfuncs chdir () { #Directory and prompt change program #syntax: Chdir Directory if [! -D "$ 1"] THEN Echo "$ 1 is not a directory" exit 1 FI CD $ 1 PS1 = `PWD` $ export ps1;} Perform: $. Persfuncs $ ChDIR TEMP / HOME / HBBWORK / TEMP $ can also be used in your own .profile file. .PERSFUNCS call. Description: Alias: Alias ​​has been used in Bash / TCSH, which is more convenient than this method than this method. 5. Definition of Shell's Special Discussion (1) Stress of the shell program: programmer (person) always makes mistakes, and computer is not wrong. Use -X to track execution, execute and display each instruction. (2) The command group has a group of commands, and these commands are completed by sub-shells; {command_list;} is executed in the front shell. The main difference between the two is its impact on the shell variable, the command executed by the child does not affect the variables in the current shell. $ Number = 2 $ (a = 2; b = 2; Number = `EXPR $ A $ B`; Echo $ Number) 4 $ Echo $ Number 2 $ = 2; b = 2; Number =` EXPR $ A $ B`; Echo $ Number;} 4 $ Echo $ Number 4 Summary: The basic knowledge of Bourne Shell is described in this chapter, using the shell variable, the shell script foundation. These concepts are very useful for understanding Korn shell, CSH, and other Script programming. Many OS have many languages ​​and some script features, but there are very little Stript script language capability like UNIX Shell.

转载请注明原文地址:https://www.9cbs.com/read-59890.html

New Post(0)