Linux bash script

Source: Internet
Author: User
Tags echo display

Linux bash script concise manual! Script Execution and debugging 1. absolute path execution. The file must have the execution permission. 2. Execute the sh command without the execution permission. 3 ,. add space or source to execute the command. The script will be executed in the current shell. 4. Check the script syntax bash-v test. sh5. Execute bash-x test. sh www.2cto.com! Environment script execution rules User Logon:/etc/profile ,~ /. Bash_profile ,~ /. Bash_login ,~ /. Profile user logout :~ /. Bash_logout execute the new shell:/etc/bash. bashrc ,~ /. Bashrc executes the script (use #! /Bin/bash): If you specify the value of BASH_ENV, execute the script in the specified Startup File #! /Bin/sh): Do not call any environment scripts! Basic Syntax 1. script program #! Start with/bin/bash. To tell the shell used by the system script. 2. A row starting with # is considered as an annotation and is automatically ignored during execution. Www.2cto.com 3. Each row must contain no more than 255 bytes. You can add a backslash to the end of the row to split the content of a single row into multiple rows. For example, test1 = abcdefg \ hij \ klmnopq \ rstuvwxyz4. When multiple commands are separated by semicolons, the commands are executed from left to right. For example: whoami; w5. When multiple commands are separated by &, execute the command from left to right in sequence based on the principle that the preceding command is successfully executed and then the next command is executed. For example, when make & make install6 and multiple commands are separated by |, execute the command from left to right in sequence according to the principle that the previous command fails to be executed before executing the next command. 7. If multiple commands are separated by semicolons (), the sub-shell is enabled and executed. For example: (mkdir testdir; cd testdir; touch testfile) 8. Multiple commands are separated by semicolons and placed in {}. The command is executed in the current shell. Note that the command and {} must have a space interval, and the last command must also have a plus sign. For example: {mkdir testdir; cd testdir; touch testfile;} 9. shell directly references the execution result of a command enclosed by backquotes or $ (command. For example, test = 'date' test = $ (date) 10. You can evaluate the arithmetic formula in the form of $ [arithmetic formula. Note that the arithmetic formula and [] must be separated by spaces. This method only supports integer calculation. For example, test = $ [32*17] 11. You can perform an arithmetic operation to evaluate the value in the form of $ (arithmetic formula) and perform a Boolean operation. For example, test = $ (32*17) 12. You can use the let formula to perform arithmetic operations. The elements in the arithmetic formula must not contain spaces, otherwise, the arithmetic formula should be enclosed in quotation marks. For example, let ++ test13. After any command is executed, a value ranging from 0 ~ Integer return code between 255. The main values are as follows: 0: normal end 1: General execution error 2: Misuse of shell Command 126: Command not executable 127: Command not found 128: invalid exit parameter 130: force stop by ctrl-c 255: Exit status code out of bounds shell script returns the return code of the last command by default. You can use exit to exit script execution and return the specified return code. For example, exit 15 is passed through $? This system variable can get the return code of the previous command. Example: syncecho $? 14. Use the getopts command to obtain the command line options. Syntax: getopts option row option variable. The option line consists of a single character of each option. If an option character requires a parameter, a colon is added after the option character. When this option is called and there is no parameter, the system will prompt an error. If you do not want the prompt to appear, you should add a colon at the beginning of the Option line. The system saves the parameter to the OPTARG variable. Example :#! /Bin/bashwhile getopts: a: bc optdo case $ opt in a) echo "option a, followed by the parameter: $ OPTARG"; B) echo "option B"; c) echo "option c"; *); esacdone15. Use mktemp to create a temporary file. The syntax is: mktemp. If the temporary file template is created successfully, 0 is returned. Temporary file template format:/tmp/test. XXXXXX or/usr/ttt/tttt. XXXXXX. The last six characters in the file name must be XXXXXX. after the generation is successful, the system will replace it with 6 random characters. Option-q does not generate error messages. Option-p specifies the parent directory for creating temporary files. The parent directory must already exist. For example, mktemp-p/usr/tmp tf. XXXXXX option-t: create a temporary file according to the parent directory specified in the environment variable TMPDIR. If the variable is not defined, the parent directory is the/tmp option-d and a temporary directory is created. Run mktemp directly. A temporary file in the form of tmp. XXXXXX will be created under the/tmp directory. The last six characters of the file name are random characters. You can use the following method to obtain the generated file name. $ Tmpfile = $ (mktemp )! Variable 1: The name of a variable can contain English letters, numbers, and underscores (_). It must start with an English letter and be case sensitive. 2. Each shell has its own variable definition, which does not affect each other. 3. variables are directly assigned with equal signs. Note that they cannot be left blank on both sides. If there is a space on the right of the equal sign, the value should be enclosed in quotation marks. For example, test = 1 test = 'Hello world' 4. Get the variable value by adding $ before the variable name. You can also use $ {variable name} to distinguish between the variable name and the following letter or underline. For example: $ {test} 5. Get the length of the variable value string in the form of $ {# variable. For example, test = '000000'; echo $ {# test} # outputs 56. You can declare a variable as a global variable. The global variable has a range of all shells. Command: xport variable name: export test7. Use unset to unregister the variable. Note that cancellation is only limited to the current shell, even if the global variable is the same. Unset-v variable name, for example, unset test8. How to clear the variable: variable name = example: test = 9. Use variable name = for Array variables (member value 1 member value 2 ...) in the form of value assignment, the member values are separated by spaces. For example, the $ testarray = (1 2 'abc' 38) array value is obtained in the form of $ variable name [subscript]. The subscript is counted from 0. For example, $ testarray [2] can get all the members of the array through $ {variable name [@]} or $ {variable name [*]}. The difference is, the former is output by each member separately, and the latter is output by all members in the form of a single string. You can use $ {# variable name [@]} or $ {# variable name [*]} to obtain the number of array members. For example: $ {# testarray [@]}. Note that the subscript of an unset array member is not removed. Example: testarray = (1 2 3 4 5 6) unset testarray [2] echo testarray [2] # echo testarray [3] # output 410. You can use readonly to declare a variable as a read-only attribute. For example: readonly test # declare the test variable as read-only readonly-f testfunc # declare the testfunc function as read-only readonly-a testarray # declare the testarray array as read-only 11. bash shell can declare the variable through declare. For example: declare-a testarray # define an array variable declare-I test # define an integer variable declare-r test # define a read-only variable declare-t test # Set the variable to have the trace attribute declare-x test # defines an environment variable 12. shell provides a set of commands to check whether the variable exists or is empty, perform the corresponding operation based on the detection result. The list is as follows: $ {Variable:-string} if the variable exists and has a value, the variable value is returned; otherwise, the string content is returned. $ {Variable: = string} if the variable exists and has a value, return the variable value. Otherwise, assign the string to the variable and return the string content. $ {Variable :? String} if the variable exists and has a value, the variable value is returned. Otherwise, the string is displayed as an error message and the script is executed. $ {Variable: + string} if the variable exists and has a value, the string content is returned. Otherwise, a null value is returned. Note: Remove: from the command to check whether the variable exists and whether it is null. 13. You can use the $ {Variable: Start position: intercept length} form to retrieve substrings through rows. If the string is taken from the starting position to the end of the string, the truncation length can be omitted. Example: test = "12345679" echo $ {test: 1: 3} # output 234 echo $ {test: 2} # output 345678914. You can run the command to Delete and replace the variable value in this line. The list is as follows: $ {Variable # matching formula} matches and deletes a substring from the left shortest according to the matching formula. $ {Variable ## matching formula} matches and deletes a substring from the left greedy String Based on the matching formula. $ {Variable % matching formula} matches the substring from the right shortest according to the matching formula and deletes it. $ {Variable % matching formula} matches and deletes the substring from the right greedy match according to the matching formula. $ {Variable/matching type/replacement string} is replaced with the replacement string from the first substring matching left. $ {Variable // matching type/replacement string} replace all substrings with replacement strings Based on matching. $ {Variable/# matched type/replacement string} is replaced with the replacement string from the first substring of the Left matching according to the matching formula. $ {Variable/matching type/} matches and deletes the first substring from the left according to the matching type. $ {Variable // matching type/} matches and deletes all substrings from the right according to the matching type. $ {Variable/# matching type/} matches and deletes the first substring from the left according to the matching type. $ {Variable/% matching formula/} matches and deletes all substrings from the right according to the matching formula.! Flow Control Command 1. if condition to command basic format: if command Athen command... else command... fi nested format: if command Athen command... elif command Bthen command... elif command Cthen command ......... fi if the return code of the command followed by if is 0, the command after then is executed; otherwise, the command after else is executed. If and then can be placed in one line, provided that if is followed by the command plus points. For example, if test-r/etc/passwd; then cat/etc/passwd; fi 2. Command basic format for case Condition Selection: case variable in matching string 1) command ...;; match string 2) command ...;;............ match string n) command ...;; *) command ...;; esac matching string format: exact match of a string. * Any string of any length, including an empty string. For example, j * k matches jack and jak .? Single character. Example: j ?? K. It matches jack but does not match jak. [] Character set. For example: [a-c] OK, matching aOK, bOK, and cOK. | Matches Multiple matching strings. Example: j ?? K | [a-c] OK | jak. If the extglob option is enabled, advanced matching is supported. Shopt-s extglob? (Matching string) matches 0 or 1 matching string in parentheses. * (Matching string) matches 0 or more matching strings in brackets. + (Matching string) matches the matching string in one bracket. @ (Matching string) matches one of the matching strings in brackets .! (Matching string) matches a matching string that is not in parentheses. 3. Basic for loop Command Format 1: for variable in IFS separator defined string do command... done processing basic string: for I in 1 2 3 4 5 6 7 8 9do echo $ idone retrieving strings from a file processing: for I in $ (cat/etc/passwd) do IFS_old = IFS = ':' for j in $ I do echo "$ j" done echo "-------------------------" done traverses directories with wildcards: for I in/etc/* do if [-f "$ I"]; then echo "$ I is the file" fidone Basic Format 2: for (initialization; end condition judgment; parameter change) do command... done is similar to the C language. For (I = 1, j = 1; (I + j) <= 100; I = I + 1; j = j + 1 )) do echo "$ I, $ j" done 4. Basic while LOOP Command Format: while condition judgment do command... done executes the loop body when the condition meets the condition criteria. Basic Application: I = 0 while ($ I <10) do echo $ I = $ ($ I + 1) done reads content from the file: while read linedo echo $ linedone <"/etc/passwd" 5. Basic Format of the until loop command: Determine the do command by the until condition... done executes the loop body when the condition does not conform to the condition criterion. 6. select the basic command format from the select menu: select variable in IFS-defined separator-separated string line do command ...... done splits the string into several items based on the delimiter defined by IFS. After the number is displayed in the list, the output is displayed, and the content defined by the Environment Variable PS3 is displayed as a selection prompt. Perform operations based on the user selection. For example: PS3 = "select: "select sel in" Test 1 "" test select 2 "" test select 3 "" Exit select "do case $ sel in" Test 1 ") echo" Test 1 ";; "Test selection 2") echo "Test 2"; "test selection 3") echo "Test 3"; *) break; esacdone 7, break command, abort and jump out of the current loop body. 8. Run the "continue" command to end the loop and continue the next loop. 9. Conditional judgment command the conditional judgment command is used in combination with the process control statement. Command Format: The test condition returns the value of the condition. If the condition is true, 0 is returned. Otherwise, a non-0 value is returned. Generally, the test command is replaced by the [condition criterion] format. Note that the condition criterion and [] must be separated by spaces. The variables to be judged must have been initialized and are not empty. For example: [-e ~ /. Bashrc] condition judgment supports compound condition judgment: A. Use the two judgment commands separated. For example: [-e ~ /. Bashrc] & [~ /. Bashrc-nt/etc/passwd] B, or use | to separate two judgment commands. For example: [-e ~ /. Bashrc] | [~ /. Bashrc-nt/etc/passwd] C. It is not used for judgment! Symbol for non-judgment. Example :! [-E ~ /. Bashrc] Conditional judgment includes four types of operations: Numerical judgment, string judgment, file judgment, and compound judgment. They are defined as follows: a. Numerical judgment [n1-eq n2] # judgment n1 = n2 [n1-ge n2] # judgment n1> = n2 [n1-gt n2] # judgment n1> n2 [n1-le n2] # determine n1 <= n2 [n1-lt n2] # determine n1 <n2 [n1-ne n2] # determine n1! = N2 Note: only integer types are supported for numerical determination. B. String judgment [str1 = str2] [str1! = Str2] [str1 <str2] [str1> str2] [-n str1] # judge whether the str1 length is not 0 [-z str1] # judge whether the str1 length is 0 C, and the file determine [-d file] # determine whether the directory file exists [-e file] # determine whether the file exists [-f file] # determine whether the file exists [-r file] # determine whether the file exists and is readable [-s file] # determine whether the file exists and not empty [-w file] # determine whether the file exists and can be written to [-x file] # determine whether the file exists and you can run [-O file] # To determine whether the file exists and belongs to the current user [-G file] # To determine whether the file exists and whether the default group is the same as the current user's group [file1-nt file2] # determine if file1 is newer than file2 [file1-ot file2] # Determine whether file1 is older than file2 D, composite judgment-a and operation, for example: [-e file-a-r file]-o or operation, for example: [-e file-o-r file] Conditional judgment can be performed using () Standard mathematical operators for numerical value assignment and judgment. Example: test = 3if ($ test * 3> 1); then echo $ testelse echo $ (++ test )) you can use [[] to compare strings for fi condition determination, and provide the regular expression matching function. Note that the limit and [,] must be separated by spaces. And there must be no spaces between the elements of the 'struct' formula. Example: test = "aaabbb123" if [[$ test = 'a']; then echo okfi! Function 1. Basic Format: function name () {command ......} 2. brackets after the keyword function and function name can be omitted separately, but cannot be ignored at the same time. The Return Value of the last command is the return code of the function by default. You can use the return command to immediately end function execution and use the value specified after return as the return code. If return is not specified, 0 is returned. The function must be defined before the first call. We recommend that you define the function at the beginning of the program. Functions can be uniformly defined in a separate file, and then called by other programs in the form of source or. (note. There is a space later. To avoid conflicts, we recommend that you start with a line below the name of the function defined in the function package. The local variables in the function should be defined by the local keyword. A function is called directly by function name. If you need to input a parameter, the function name is followed by a space. Multiple parameters are separated by spaces. The input location parameters are called in the form of the function and $ n, and the location parameters of the main program are not affected. Example: func. sh #! /Bin/bash_testfunc () {if ($1> $2); then echo "$1> $2" elif ($1 = $2 )); then echo "$1 = $2" else echo "$1 <$2" fi return 10} main. sh #! /Bin/bash. func. sh_testfunc 32 24_testfunc 15 15_testfunc 1 12! Commonly used built-in commands 1. echo display information, automatic line feed echo-n cancel Automatic line feed echo-e control character takes effect, for example, if the information displayed by \ necho contains spaces, It is enclosed by single quotation marks or double quotation marks. The content enclosed in double quotation marks will escape the variable values, calculation results, command execution results, and escape characters before output. The content enclosed in single quotes is directly output without any conversion. Example: echo "it's me" # output it's metest = lykyl; echo '$ test' # output $ test. If the display information includes variables, the variable value is obtained and then combined with the string. For example, test = lykyl; echo "hello $ test" # outputs hello lykyl. If you want to output $ characters, you can use escape characters or enclose strings in single quotes. For example: test = lykyl; echo-n 'Hello $ test'; echo "\ $ test" # output hello $ test $ test2,: Return 03, eval parsing string parameters, execute in command Form 4. source execute the specified shell program in the current shell. For example, the source func. sh6 and readread variable names are used to obtain user input and store the input content in the variables following the command. If no variable is specified, it is stored in the REPLY variable by default. After the read-p 'prompt info' variable name displays the prompt information, wait for the user to enter it. The read-a variable name accepts a set of values separated by spaces and stores them in the specified variable. The read-r variable name read command removes the backslash before the escape character by default. For example, enter \ n to store the variable and only n is allowed. After the-r option is added, the read command will accept escape characters without filtering. The variable name of the read-t wait duration is set to the length of the read wait input. After the timeout, the read operation returns a non-zero value. The read-s variable name hides the echo of user input content on the screen. 7. execexec command to execute the command to replace the current shell. Exec <the file name is switched to the input, and the data is read from the standard input to the specified file. 8. The command after the eval command is executed. For example, showfile = '/etc/passwd' eval "cat $ showfile" 9. expr returns arithmetic values. Note that the operators should be separated by spaces, escape operators that conflict with system controllers. For example, expr 1 + 1 expr 2 \ * 310 and bc calculator can use bc to enable shell script to process floating point operations. The bc built-in variable scale controls the exact digits after the decimal point. A. Simple operations use pipelines to separate multiple operators with semicolons and send them to bc. The values of the rightmost operators are output after being executed from left to right. Echo "Formula 1; formula 2 ;... "| bc example: num = 33var = 'echo" scale = 3; v = 5 * $ num; v3 = v/4; v3 + 1 "| bc 'B. complex operations perform more complex operations through inline input redirection. Example: num = 33var = 'bc <EOFscale = 2v1 = 15.5v2 = 34 * v1v3 = $ num * v2 + 3v1*(v2 + v3/2) EOF '! Common system variables 1, $0 currently executed shell script file name (with full path) 2, $1 ~ $ N stores shell script command line parameters in sequence. If the value is greater than 9, it must be included in {}, for example, ${10 }. The command line parameter can be displaced by the shift command. The position parameter moves forward based on the value specified by the shift command. If the value is not specified, it is moved once. Example: www.2cto.com #! /Bin/bashecho "all input parameters: $ @ "while shiftdo [-n" $1 "] & echo $1done3, $ * save all command line parameters as a string to this variable. 4. $ @ Use all command line parameters as a string array. Each parameter is a member variable and saved to this variable. 5. $ # Number of command line parameters. 6. $? The return code after the previous command is executed. 7. $ the number of the currently executed shell script process. 8. $! The process ID of the previous background program. 9. When $ _ script is executed, it stores the absolute path of bash. During bash interaction, the last command line parameter of the previous command is stored. The email file name is stored during email detection. Source http://www.cnblogs.com/lykyl/archive/2013/02/15/2912764.html
 

Related Article

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.