Common tips for writing shell in linux: shell environment variable $ IFS usage 1IFS default value: Blank (including space, tab, and New Line ), to print out its asⅱ code in hexadecimal format, the processing of space white space in 20090a2IFS is different from that of other characters. the common skills of shell writing in the left and right linux systems are as follows: shell environment variable $ IFS usage 1. the default value of IFS is: Blank (including space, tab, and New Line). print the asⅱ code in hexadecimal format: 20 09 0a 2. the processing of spaces in IFS is different from that of other characters. the pure white spaces in the left and right sides are ignored, and multiple consecutive white spaces are treated as one IFS. Use the first character in IFS in 3. S. 4. the FS (domain separator) in awk has similar usage and functions as IFS. Shell environment variable $ IFS usage S indicates Internal Field Separator (Internal Field Separator) example: $ IFS =: $ a = Hello: World $ echo $ a output result is: the example of "Hello World" instead of "Hello: World" illustrates how to read and operate a specific field from a data file in a Linux shell script. For example, the format of the hypothetical file employees.txt is {employee-name }:{ employee-id }:{ department-name}, which is divided by a colon, as shown below. $ Cat employees.txt Emma Thomas: 100: Marketing Alex Jason: 200: Sales Madison Randy: 300: Product Development Sanjay Gupta: 400: Support Nisha Singh: 500: the shellscript in the Sales section describes how to read a specific field from the employee.txt file ). $ Vi read-employees.sh #! /Bin/bash IFS =: echo "Employee Names:" echo "---------------" while read name empid dept do echo "$ name is part of $ dept department" done <~ /Employees.txt grant the script executable permission and then execute this script. 2. the special symbols commonly used in shell are listed as follows: #;., // \ 'string' |! $ {}$? $ * \ "String \"***?: ^ $ # $ @ 'Command '{} [] [[] () | & {xx, yy, zz ,...}~ ~ + ~ -& \\<... \\> +-% =! = # Comments: This is almost a full-site symbol, except for the previous \ "first line \"#! The/bin/bash well number usually appears at the beginning of a line or after the complete command. This type of situation indicates that the annotation text is followed by the symbol and will not be executed. # This line is comments. echo \ "a = $ a \" # a = 0 due to this feature, when you do not want to execute a certain line of command temporarily, you only need to add # at the beginning of the line. This is often used in the writing process. # Echo \ "a = $ a \" # a = 0 if it is used in the instruction, or enclosed in double quotation marks, or after the backslash, then it becomes a general symbol and does not have the above special functions. ~ The home directory of the account is a common symbol, representing the home directory of the User: cd ~; You can also add the account name "cd ~" directly after the symbol ~ User or a part of the path :~ /Bin ~ + The current working directory. this symbol represents the current working directory. it serves the same purpose as the built-in command pwd. # Echo ~ +/Var/log ~ -Last working directory. this symbol represents the last working directory. # Echo ~ -/Etc/httpd/logs; in the shell, the semicolon (Command separator) serves as the \ "continuous instruction \" function symbol is \ "Semicolon \". For example, cd ~ /Backup; mkdir startup; cp ~ /. * Startup/.; the consecutive semicolon (Terminator) is dedicated to the case option and serves as the Terminator role. Case \ "$ fop \" inhelp) echo \ "Usage: Command-help-version filename \"; version) echo \ "version 0.1 \"; esac. in shell, the user should be clear that one dot represents the current directory, and two dots represent the upper directory. CDPATH = .:~ :/Home/web:/var:/usr/local in the upstream CDPATH setting, the dot after the equal sign represents the meaning of the current directory. If the file name starts with "dot", the file is a special file, which is displayed only when the-a option is added to the ls command. In regularexpression, a dot represents matching a character. The content enclosed by single quotes in 'string' is considered a single string. The $ symbol representing the variable in quotation marks does not work. that is to say, it is treated as a general symbol to prevent replacement of any variable. Heyyou = homeecho '$ heyyou' # The content enclosed by double quotes is considered a single string. It prevents wildcard extension, but allows variable extension. This is different from how a single reference is processed. Heyyou = homeecho \ "$ heyyou \" # We get home 'command' inverted quotation marks (backticks) in front of a single double quotation mark, enclosed by a string, but what if the string is a command column? The answer is no execution. To handle this situation, we must use single quotes. Fdv = 'date + % f' echo \ "Today $ fdv \" The date + % F in the inverted quotation mark is considered as an instruction, and the execution result is included in the fdv variable., Comma (comma in punctuation), which is often used in operations as \ "segmentation. Example #! /Bin/bashlet \ "t1 = (a = 5 + 3, B = 7-1, c = 15/3) \" echo \ "t1 = $ t1, a = $ a, B = $ B \ "/forward slash indicates a directory in the path. Cd/etc/rc. dcd.../. cd/usually a single/represents the root directory. in the four arithmetic operations, it represents the division symbol. Let \ "num1 = (a = 10/2, B = 25/5) \" \ the escape character in interactive mode, which has several functions. before the command, the function of canceling aliases. if it is placed before a special symbol, the function of the special symbol disappears. if it is placed at the end of the command, it indicates that the command is connected to the next line. # Type rmrm is aliased to 'rm-I '# \ rm. /*. in the log example, I add the escape character before the rm command to temporarily cancel the alias function and restore the rm command. # Bkdir =/home # echo \ "Backup dir, \\$ bkdir = $ bkdir \" Backup dir, $ bkdir =/\ $ bkdir in echo in the home instance, escape cancels the $ variable function. Therefore, $ bkdir is output, while the second $ bkdir outputs the variable content/home. | Pipeline is a basic and important concept of UNIX systems. Connect the standard output of the previous command as the standard input of the next command. Who | wc-l makes good use of this concept, which is quite helpful for streamlining scripts.! The exclamation point (negate or reverse) usually represents the anti-logic function. for example, it is used in condition detection! = To represent \ "not equal to \" if [\ "$? \"! = 0] thenecho \ "Executes error \" exit 1fi in the rule expression, she assumes the \ "anti-logic \" role ls [! 0-9] In the preceding example, other files except a0, a1... a9 are displayed.: Colon in bash, this is a built-in command: \ "do nothing \", but return the status value 0.: Echo $? # The response is 0:> f. $. the above line is equivalent to cat/dev/null> f. $. Not only is the statement short, but the execution efficiency is much higher. Sometimes, the following usage occurs: $ {HOSTNAME ?} $ {USER ?} $ {MAIL ?} This line is used to check whether these environment variables have been set. if they are not set, an error message is displayed as a standard error. Similar to test or if, this type of check can basically be processed, but it is not as concise and efficient as in the previous example.? Question mark (wild card) plays a role on Filename expansion that matches any character but does not contain null characters. # Ls? A1 makes good use of her features to perform exact file name matching. * Asterisks (wild card) are commonly used symbols. In Filename expansion, it represents any character and contains null characters. # Ls a * a a1 access_log during operation, it represents \ "multiplication \". Let \ "fmult = 2*3 \" in addition to the built-in command let, there is also an expr command about the operation, the asterisk here also serves as the \ "multiplication \" role. However, be careful when using the escape character. ** Two asterisks in the power operation mean the table \ "\" in the operation age. Let \ "sus = 2 ** 3 \" echo \ "sus = $ sus \" # sus = 8 $ dollar sign Variable replacement (Variable Substitution) representative symbol. Vrs = 123 echo \ "vrs = $ vrs \" # vrs = 123 in addition, in Regular Expressions, it is defined as the end-of-line ). This is often used in grep, sed, awk, and vim (vi. The regular expression of $ {} variable bash defines many usage for $. The following table columns are from the online description $ {parameter:-word }$ {parameter := word }$ {parameter :? Word }$ {parameter: + word }$ {parameterffset: length }$ {! Prefix * }$ {# parameter }$ {parameter # word }$ {parameter % word }$ {parameter/pattern/ string }$ {parameter // pattern/string} $ * reference the execution reference variable of the script, the algorithm for referencing parameters is the same as that for general commands. The Command itself is 0, followed by 1, and so on. Variables referenced are represented as follows: $0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $ {10}, ${11 }..... for single-digit users, you can directly use a number. if the number is greater than two digits, you must use the {} symbol to enclose it. $ * Indicates all symbols that reference variables. Double quotation marks must be added as needed. Echo \ "$ * \" has a symbol with the same effect as $ *, but its utility and processing method are slightly different. $ @$ @ Has the same effect as $ *, but there is a difference between them. Symbol $ * considers all referenced variables as a whole. But the symbol $ @ still retains the concept of block for each referenced variable. $ # This is also a symbol related to the referenced variable. her role is to tell you the total number of referenced variables. Echo \ "$ #\" $? Status variable generally, UNIX (linux) processes end with the execution system calling exit. The return value is the status value. It is returned to the parent process to check the execution status of the child process. If the command program is successfully executed, the return value is 0; if the command program fails, the return value is 1. Tar cvfz dfbackup.tar.gz/home/user>/dev/nullecho \ "$? \ "$ Because the process ID is unique, it is impossible to have a repetitive PID at the same time. Sometimes, scripts need to generate temporary files to store necessary information. This script may also be used by users at the same time. In this case, the fixed file name is obviously unreliable in writing. Only dynamic file names can be generated. Symbol $ may meet this requirement. It represents the PID of the current shell. Echo \ "$ HOSTNAME, $ USER, $ MAIL \"> ftmp. $ Use it as a part of the file name to avoid overwriting of the same file name at the same time. Ps: basically, the system recycles the executed PID and then allocates it as needed. Therefore, even if the temporary file is written using the dynamic file name, other problems may occur if the script is not cleared after execution. () Command group enclose a string of continuous commands in parentheses. this is called a command group for shell. Example: (cd ~; Vcgh = 'pwd'; echo $ vcgh), the command group has a feature, shell will generate subshell to execute this set of commands. Therefore, the variables defined in the variable only act on the command group itself. Let's look at an example # cat ftmp-01 #! /Bin/basha = HCG (a = incg; echo-e \ "\ n $ a \ n \") echo $ #. /ftmp-01incgfsh in addition to the preceding command group, brackets are also used in the definition of array variables; also applied in other occasions that may require the escape character to be used, such as the formula. () The role of these symbols is similar to that of the let command. it is used in arithmetic operations and is a built-in function of bash. Therefore, the execution efficiency is much better than using the let command. #! /Bin/bash (a = 10) echo-e \ "in1_value, a = $ a \ n \" (a ++ )) echo \ "after a ++, a = $ a \" {} braces (Block of code) sometimes appear in scripts, a section or segments ending with \ "Semicolon \" are enclosed in braces to set the instruction or variable. # Cat ftmp-02 #! /Bin/basha = HCG {a = inbc; echo-e \ "\ n $ a \ n \"} echo $ #. /ftmp-02inbcinbc this usage is very similar to the command group described above, but there is a difference that it is executed in the current shell, does not produce subshell. Braces are also used in the \ "function \" function. Broadly speaking, simply using braces only serves as a function without a specified name. Therefore, writing scripts in this way is quite good. This method can simplify the complexity of the script, especially for the output input. In addition, braces have another usage, as shown in {xx, yy, zz ,...} this combination of braces is often used in string combinations. let's look at the mkdir {userA, userB, userC}-{home, bin, data} example. we get userA-home, userA-bin, userA-data, userB-home, userB-bin, userB-data, userC-home, userC-bin, and userC-data. This set of symbols is widely applied. If you can make good use of it, the return is simplified and efficient. In the following example, chown root/usr/{ucb/{ex, edit}, lib/{ex ?.? *, How_ex} if this usage is not supported, we have to write several rows and repeat them several times! [] Brackets are often used in process control and play the role of the square brackets. If [\ "$? \"! = 0] the thenecho \ "Executes error \" exit1fi symbol serves as the rm-r 200 [1234] role similar to \ "range \" or \ "set \" in the regular expression., indicates deleting directories such as 2001,200 2 and 2003,200 4. II. format: sed-I "s/search field/replace field/g" 'grep search field-rl path 'Linux sed batch replace strings sed-I "s/oldstring/newstring in multiple files /g "'grep oldstring-rl yourdir' example: replace www.admin99.net with admin99.net sed-I "s/www.admin99.net/admin99.net/g" 'grep www.admin99.net-rl/home' exp: sed-I "s/shabi/$/g" 'grep shabi-rl. /'
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.