Linuxbashscript concise Manual

Source: Internet
Author: User
Tags echo display
Linuxbashscript 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-vtest .... 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 Str2] [-n str1] # judge whether the str1 length is not 0 [-z str1] # judge whether the str1 length is 0 C, and the file judge [-d file] # determine whether the directory file is [-e file] # determine whether a file exists [-f file] # determine whether a file exists [-r file] # determine whether a file exists and is readable [-s file] # determine whether the file exists and not empty [-w file] # determine whether the file exists and write [-x file] # determine whether the file exists and execute [-O file] # determine whether the file exists existing and belongs to the current user [-G file] # determine whether the file exists and whether the default group is the same as the current user's group [file1-nt file2] # determine whether file1 is newer than file2 [file1 -ot file2] # determine whether file1 is older than file2 D, composite judgment-a and operation, example For example, [-e file-a-r file]-o or operation. for example, the condition [-e file-o-r file] can be determined (()) use standard mathematical operators to perform 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 <  
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.