Shell script summary and tips in script writing

Source: Internet
Author: User
Simple summary of Shell scripts and tips in script writing mainly summarize the entry-level bash from the following aspects: 1. Command History, command completion 2. pipelines, redirection 3. command alias and command replacement 4. command line editing 5. file name wildcard 6. Bash-related configuration files and variables 7. programming (entries... simple summary of Shell scripts and tips in script writing mainly summarize the entry-level bash from the following aspects: 1. Command History, command completion 2. pipelines, redirection 3. command alias and command replacement 4. command line editing 5. file name wildcard 6. Bash-related configuration files and variables 7. programming (condition judgment and loop control) 8. array 9 in bash, shell programming skills and programming specifications 1. View command history and command completion Command history: history-c: clear command history-d OFFSET [n]: delete command-w at the specified position: save command history to History Files. this is useful for executing commands on different terminals :! N: The Nth command in the execution history ;! -N: the last n commands in the Command History ;!!: Execute the previous command ;! String: The most recent command in the execution history that starts with a specified string! $: Reference the last parameter of the previous command; Esc ,. alt +. command completion, PATH completion command completion: Searches for executable files starting with the string given in each PATH specified by the PATH environment variable. if there is more than one executable file, tab twice, A list can be provided; otherwise, the list will be completed directly; path completion: Search for each file name in the given starting path, and try to complete; 2. pipeline, redirect pipeline ------ output of the previous command, enter Command 1 as the next command | Command 2 | Command 3 |... for example: cat/var/log/message | less find. /-name ex * | xargs mv/backup> overwrite output> append output 2> redirect error output 2> append Method &> redirect standard output or error output to the same file <enter redirection <Here Document:> for example, cat>/etc/hos Ts <EOF 201710000172.28.9.47www03.opsmysql.com 172.28.9.48www04.opsmysql.com EOF "*/5 *****/usr/sbin/ntpdate ntp. api. bz>/dev/null 2> & 1/dev/null 2> & 1: this means to redirect all standard output and error output to/dev/null. 3. replace the COMMAND alias = 'command [options] [arguments] 'in the shell. the defined alias is only valid in the current shell lifecycle; the alias is valid only for the current shell process. for commands that we set the alias for ualias alias, if you want to use the command format when the alias is not set, that is The default format can be added before the command: \ CMD for Alias, we can also write in the configuration file: global configuration file:/etc/bashrc user configuration file :~ /. Bashrc COMMAND replacement: $ (COMMAND), reverse quotation mark: 'command' replaces a subcommand with The execution result, for example, echo "The date time is: 'date' "echo" The date time is: $ (date + % F) "bash-supported quotation marks:'': Command replacement "": Weak reference, you can replace ''with variables: strong reference, not complete variable replacement 4. edit the command line cursor jump: Ctrl + a: Jump to the beginning of the command line Ctrl + e: jump to the end of the command line Ctrl + u: delete the content from the cursor to the beginning of the command line Ctrl + k: delete the content from the cursor to the end of the command line Ctrl + l: clear screen 5, file name wildcard: globbing *: any character of any length?: Any single character []: match any single character within the specified range [abc], [a-m], [a-z], [A-Z], [0-9], [a-zA-Z], [0-9a-zA-Z] [: space:]: blank character [: punct:]: punctuation [: lower:]: lowercase letter [: upper:]: upper-case letter [: alpha:]: upper-case letter [: digit:]: number [: alnum:]: numbers and uppercase/lowercase letters # man 7 glob [^]: match any single character out of the specified range [[: alpha:] * [[: space:] * [^ [: alpha:] 6. Bash-related configuration files and variable bash configuration files: global configuration/etc/profile,/etc/profile. d /*. sh,/etc/bashrc personal configuration ~ /. Bash_profile ,~ /. Bashrc profile File: Set the environment variable run command or script bashrc class File: set the local variable definition command alias logon shell how to read the configuration file? /Etc/profile -->/etc/profile. d/*. sh --> ~ /. Bash_profile --> ~ /. Bashrc -->/etc/bashrc non-login shell how to configure the file? ~ /. Bashrc -->/etc/basrc -->/etc/profile. d /*. sh introduction to environment variable commands: 1. echo shows the value of an environment variable echo $ PATH 2. export sets a new environment variable export HELLO = "hello" (no quotation marks are allowed) 3.env displays all environment variables 4.set display locally defined shell variables 5. unset clear environment variable unset HELLO 6. readonly sets readonly environment variable readonly HELLO common environment variable PATH: determines which directories the shell will look for commands or programs HOME: current user HOME Directory MAIL: it refers to the current user's mail storage directory SHELL: refers to the current user's Shell HISTSIZE: refers to the number of historical command records stored LOGNAME: refers to the current user's login name HOSTNAME: host name. if host names are used by many applications, Usually obtained from this environment variable LANG/wide GE: it is a language-related environment variable, users in multiple languages can modify this environment variable PS1: is a basic prompt, for the root user is #, for the common user is $ PS2: is the affiliated prompt, the default is "> ". You can modify this environment variable to modify the current command operator location variable: $1, $2,... $ n special variable: $?: Return value of the execution status of the previous command. if the echo $0 result is 0, it indicates success, and if it is not 0, it indicates failure. $0: get the name of the currently executed shell script file, usually used in combination with basename $ *: Get all parameters of the current shell, $1 $2 $3, note the difference with $ #: get the total number of parameters in the current shell command line $: get the current shell process number (PID) $!: Execute the PID of the previous command $ @: all parameters of this program "$1" "$2" "$3 ""... "Note: Sometimes the variable name is easily confused with other words. for example, we append the content after the value of a variable: num = 2 echo "this is the $ numnd" which does not print "this is the 2nd", but only prints "this is ", because shell will search for the value of the variable numnd, but this variable does not have a value. We can use curly braces to tell shell that we want to print the num variable: num = 2 echo "this is the $ {num} nd" which will print: this is the 2nd variable name cannot start with a number !!!!!!!!!!!!!!!! ++ How to perform arithmetic operations in the +++ ++ shell: A = 3 B = 6 1 ). let arithmetic expression let C = $ A + $ B 2 ). $ [arithmetic expression] C = $ [$ A + $ B] 3 ). $ (arithmetic expression) C =$ ($ A + $ B) 4 ). expr arithmetic expression. there must be spaces between the operands and operators in the expression, in addition, using commands to reference C = 'expr $ A + $ B 'is the basis of shell programming !!! Simple shell operations on strings: Take string length A = "admin" echo $ {$ A} or expr length $ A string replacement and deletion operations: $ {variable # Keyword} ---------> If the variable content conforms to the 'keyword' from the beginning, delete the compliant shortest data, for example: echo $ {variable ## Keyword} ---------> If the variable content matches the 'keyword ', delete the longest matched data $ {variable % keyword} ---------> If the variable content is forward from the end of the data ', delete the compliant shortest data $ {variable % keyword} ---------> If the variable content from the end of the data meets the 'keyword ', delete the longest matching data $ {variable/old string/new string} ---------> If the variable content conforms to the 'old string', the first old string will be replaced by the new string $ {variable // old string/new string} ---------> If the variable content conforms to the 'old string', all old strings will be replaced by new strings. 7. programming (conditional judgment) And cyclic control) the following section summarizes the expressions for the test condition test in the test file of the conditional test type integer test character: [expression] [[expression] ----- this advanced version can only be used in Bash later versions... the one above will report an error! Test expression integer comparison:-eq: test whether two integers are equal; for example, $ A-eq $ B-ne: test whether two integers are unequal; unequal, true; equal, false; -gt: test whether a number is greater than the other number. if the value is greater than or true, the value is false.-lt: test whether a number is smaller than the other number. if the value is less than, the value is true. Otherwise, the value is false; -ge: greater than or equal to-le: logical relationship between less than or equal to: logical and: & when the first condition is false, the second condition does not need to be judged, and the final result already exists; when the first condition is true, the second condition must be judged; logical OR: | note: [Condition 1-a condition 2] is equivalent to [Condition 1] & [Condition 2]. Note that: you can use [[Condition 1 & Condition 2] in this way. you cannot use a character like [Condition 1 & Condition 2] to test: =: to test whether the conditions are equal. if the conditions are true, not equal to false! =: Test whether the value is not equal to true. if the value is false, the value is \ >\<-n string: test whether the specified string is null. if it is null, the value is true. if it is not null, the value is false-z string: test whether the specified string is null. if it is null, it is true. if it is null, it is a false string = "". the string is a null string! = "" String not empty FILE test:-e FILE: Test FILE existence-f FILE: Test FILE is normal FILE-d FILE: test whether the specified path is a directory-s FILE: judge whether the FILE exists and the size is greater than 0-r FILE: test whether the current user has the permission to read the specified FILE-w FILE: whether the FILE can be written-x FILE: whether the FILE can be executed. Simply put, the script exit status code exit: exit script exit # if the script does not explicitly define the exit status code, the exit code of the last command is the exit status code of the script. generally: #0 indicates normal exit # Non-0 indicates incorrect exit + ++ ++ condition judgment-if single branch if statement if judgment condition; then statement1 statement2... fi dual-branch if statement: if judgment condition; then s Tatement1 statement2... else statement3 statement4... fi multi-branch if statement: if judgment condition 1; then statement1... elif judgment condition 2; then statement2... elif judgment condition 3; then statement3... else statement4... fi ++ ++ select the structure -- case SWITCH in value1) statement ...;; value2) statement ...;; *) statement ...;; esac description: value1) is a regular expression style. the following character can be used: * a string of any length, C *, to indicate characters starting with C. String? Any single character ,???? A string of four characters: [abc] a, B, or c. for example, [abc] 123 matches a123, b123, or c123. [A-n] any character from a to n | multiple options, delimiter ++ +++ loop control-: for variable in list; do loop body done for (expr1; expr2; expr3); do loop body done loop control --- while CONDITION; do statment done enters the loop: conditional exit loop: the condition does not meet the special usage of while 1 (Endless loop): while:; do statment done while special usage 2 (read rows from a file ): while read LINE; do statment done </PATH/TO/SOMEFILE Method 2: cat ip.txt | while read line do echo $ Line done loop control --- until is opposite to while. you can refer to while until CONDITION; do statement... done to determine whether the CONDITION is true. if it is not true, the system executes the loop body and exits when it is true! The loop control statement break interrupts the loop, and then runs the statement after the loop. by default, it jumps out of a loop. to jump out of a multi-tier loop, you can use break n (n is a number greater than 1, count ). Continue interrupts the current cycle and enters the next cycle in advance. by default, a loop is skipped. if you want to skip multiple cycles, you can use continue n (n is a number greater than 1, that is, the number of times ). ++ ++ Select (menu selection) A select expression is a bash extension application that is especially good at interactive use. you can select from a group of different values. the select command can be used to create a simple list. The structure is similar to the for loop. it is generally used in combination with the case statement. Below is an example :#! /Bin/bash echo "What is your favorite OS? "Select var in" Linux "" Gnu Hurd "" Free BSD "" Other "; do break done echo" You have selected $ var "8. array assignment in bash: (1) array = (var1 var2 var3... varN) (2) array = ([0] = var1 [1] = var2 [2] = var3... [n] = varN) (3) array [0] = var1 arrya [1] = var2... array [n] = varN note: The subscript of the array in shell starts from 0 by default! Get the number or length of array elements: (1) $ {# array [@]} (2) $ {# array [*]} display array elements: echo $ {array [*]} # show all elements echo $ {array [@]} echo $ {array [@]: 0} echo $ {array [0]} # display the first element echo $ {array [@]: 2} # Do not display the first two elements in the array echo $ {array [@]: 0: 2} # display two elements from the first element to delete the elements in the array: unset array [2] # Delete the third element unset array # delete the entire array substring: echo $ {array [@] # t * e} # start the shortest match on the left: "t * e ", this will match "thre" echo $ {array [@] # t * e} # The longest match from the left, this will match "three" echo $ {array [@] % o} # Open from the end of the string Minimum matching echo $ {array [@] % o} # Replace the longest matching substring starting from the end of the string: echo $ {array [@]/o/m} # The first matched, echo $ {array [@] // o/m} # all matched, echo $ {array [@] // o/} # is not specified to replace the substring, delete the matched sub-character echo $ {array [@]/# o/k} # Replace the string with the first terminal string echo $ {array [@]/% o/k }# after replacing the string, the terminal string cyclically lists the array elements: #! /Bin/bash arr = (AB bc cd) lenarr =$ {# arr [@]} for (I = 0; I <$ lenarr}; I ++ )); do echo $ {arr [$ I]} done #! /Bin/bash arr = (AB bc cd) lenarr =$ {# arr [@]} I = 0 while [[$ I-lt $ lenarr] do echo $ {arr [$ I]} let I ++ done instance: #! /Bin/bash # set IFS to linefeed (\ n) OLDIFS = $ IFS = $ '\ n' # read the file content to the array fileArray = ($ (cat file.txt )) # restore it IFS = $ OLDIFS tLen =$ {# fileArray [@]} # cyclically show the file content for (I = 0; I <$ {tLen }; I ++); do echo "$ {fileArray [$ I]}" done 9, shell programming skills and programming specification check syntax related: bash-n script name command tracing: bash-x script name in shell input and output: read usage cat special usage echo special usage background execution command: & nohup if a process is running, you can run the nohup command to exit the account. This command can continue running the corresponding process after you exit the account. Nohup means no hang up ). What is the general form of the nohup command? Nohup command & shift usage! To put it simply, programming specifications: 1. file comments indicate that each script file written should contain file comments, simple descriptions of script usage, versions, authors, etc. .. for example :#! /Bin/bash # Description :....... # Date: xxxx-xx # Version :.... # Author: Andy 2. code comment 3. function annotation -- describe the function 4. variable naming normalization name indicates the meaning of this variable. the variable name or function name should not be too long. try to use uppercase or uppercase to start with a name such as Passwd Num_Count.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.