8.17_linux bash Shell scripting Getting Started (iii) cycle and use of function functions

Source: Internet
Author: User
Tags echo command function definition function examples variable scope



Bash shell scripting Getting Started (iii) cycle






What is loop execution?



To run a code segment repeatedly multiple times



How many times to run repeatedly:



Number of cycles known beforehand



Number of cycles unknown beforehand



There are entry conditions and exit conditions






Related commands: For, while, Until,selet,






Use for command






Role:



Assigns the element in the list to the "variable name" in turn; The loop body is executed once each assignment; Until the elements in the list are exhausted, the loop ends






Command format:



For variable name in list; Do



Loop body (Execution command executed normally)



Statement 1



Statement 2



Statement 3



...



Done






List Generation Method:



(1) Give the list directly



(2) List of integers:



(a) {start: End



(b) $ (seq[start [step]] end)



(3) command to return a list



$ (COMMAND)



(4) using glob, such as: *.sh



(5) variable reference;



[email protected], $*






For command Example 1, add user user1-10 with a for loop





For command Example 2, show 99 multiplication table with for loop








Use of the while command






Role:



While command to judge condition: cyclic control conditions, before entering the cycle, make a judgment, after each cycle will be judged again; the condition is "true", then a loop is executed until the condition test state is "false" to terminate the loop.



Therefore: Condtion generally should have a cyclic control variable, and the value of this variable will be continuously corrected in the loop body



Entry condition: condition is true;



Exit Condition: Condition is false.






Command format



While CONDITION; Do



Loop body



Done






While command example 1, use while to ask 1: Sum of positive integers between 100





While command example 2, use while to find the maximum and minimum values for random 10 numbers





While command example 3, use while to output an international chessboard








Use of the until command






Role:



Same while, just enter the opposite condition.



Entry condition: CONDITION is False



Exit Condition: CONDITION is True






Command format:



Until CONDITION; Do



Loop body



Done






Until command example 1, the use of until randomly generated numbers within 10, to achieve the word guessing game, the hint is larger or smaller, the same exit.





Until command example 2, using until to print 99 multiplication table








Continue use of circular control statements



Use environment: used in the loop body



Continue [n]: End of the nth layer of the current cycle, and directly into the next round of judgment; the inner layer is the 1th floor.



While CONDTIITON1; Do



CMD1



...



if CONDITION2; Then



Continue



Fi



Cmdn



...



Done






Continue command example 1; when the loop matches 5, jump out of the current loop and continue to the next loop





Continue command Example 2; When the loop matches the current condition, jump out of the current loop and continue to the next loop








Use of the break of a circular control statement



Use environment: used in the loop body



Break [n]: Early end of the nth layer cycle, the inner layer is the 1th layer



While CONDTIITON1; Do



CMD1



...



if CONDITION2; Then



Break



Fi



Cmdn



...



Done






Break command Example 1, when eligible, jumps out of the current loop and executes the next echo command





Break command Example 2, when eligible, jumps out of the current loop and executes the next echo command








loop control infinite Loop (exit please press CTRL + C)



While Infinite loop: let the condition be true and let the while enter an infinite loop



While true; Do



Loop body



Done






Until Infinite loop: let the condition be false, let while enter Infinite loop



until false; Do



Loop body



Done






Special usage of the while loop (traversing each line of the file)



while read line; Do



Loop body



Done </path/from/somefile



Read each line in the/path/from/somefile file sequentially and assign the row to the variable line






Example 1, calculating the and of the UID





Example 2



Scan each line of the/etc/passwd file, if the Gecos field is found to be empty, populate the user name and unit phone with 62985600, and prompt the user for Gecos information to be modified successfully.








Special format for loop: Double parenthesis method C language-style variable manipulation






For (control variable initialization; conditional judgment expression; control variable correction expression))



Do



Loop body



Done






Double-brace method, i.e. ((...)) Format, which can also be used for arithmetic operations



The double-brace method also enables the bash shell to implement C-style variable manipulation



#I =10



# ((i++))






Control variable initialization: Executes only once when running to a loop code snippet



Correction expressions for control variables: The control variable correction operation is performed at the end of each cycle, then the condition is judged.






How it works: Execute 1-2-3-4 in the order of the symbols, then 2-3-4-2-3-4-2 the loop,



Until the condition of program 2 does not conform, jump out of the loop.









Example: printing 1 to 10 with a for double-brace C language style












Select loops and Menus



Select variable in List;do



Circular Body Command



Done



The Select loop is used primarily to create menus, and menu items in numerical order are displayed on standard errors, and a PS3 prompt is displayed, waiting for the user to enter



The user enters a number in the menu list and executes the corresponding command



The user input is saved in the built-in variable reply.






Select is an infinite loop, so remember to exit the loop with the break command, or terminate the script with the Exit command. You can also press CTRL + C to exit the loop.



Select is often used in conjunction with case



Similar to a For loop, you can omit the in list and use positional parameters at this time






Select Example:












Functional Function Description   





1) Functional function is a block of statements composed of several shell commands, which implements code reuse and modular programming.



2) It is similar to the shell program, but it is not a separate process, it cannot run independently, but is part of the shell program.



3) functions are similar to shell programs, except that:



Shell program runs in child shell



The Shell function runs in the current shell. So in the current shell, the function can modify the variables in the shell






Defining functions



Functions consist of two parts: the function name and the function body.



Syntax One:



function f_name{



... function Body ...



}



Syntax Two:



F_name () {



... function Body ...



}






function uses



Definition and use of functions:



Functions can be defined in an interactive environment



You can put a function in a script file as part of it



Can be placed in a separate file that contains only functions



Call: The function is executed only if it is called;



Call: given function name



Where the function name appears, it is automatically replaced with the function code



The life cycle of a function: created when invoked, terminated on return






Define and use function examples; define a two-digit double-plus function








function return value



The function has two return values:



The return value of the function's execution result:



(1) Output with the Echo or printf command



(2) output of the call command in the function body



Exit status code for the function:



(1) The default depends on the exit status code of the last command executed in the function



(2) Custom exit status code, in the form of:



Return returned from the function, with the last state command to determine the return value



return 0 returns without error.



Return 1-255 has error returned






Example: Custom return value









Defining and using functions in an interactive environment



Example:



ABC () {



> ls-l



>}



After defining the function, type ABC, which displays the same results as ls-l.



The ABC function will persist until the user exits from the system, or executes the unset command as follows: unset ABC







Defining and using functions in scripts



A function must be defined before it is used, so the function definition should be placed at the beginning of the script until the shell first discovers it before it can be used



The calling function uses only its name of functions.



Example:








Working with function files



You can store frequently used functions in a function file and then load the function file into the shell.



The file name can be arbitrarily selected, but it is best to have some kind of connection to the related task. Example: Functions.main



Once the function file is loaded into the shell, the function can be called from the command line or script. You can use the SET command to view all defined functions whose output list includes all functions that have been loaded into the shell.



To change a function, first remove the function from the shell with the unset command. Once the changes are complete, reload the file.






Creating a function file



Example of a function file:








Load function



Once the function file has been created, load it into the shell.



Locate the function file and load the shell into the format:



. FileName or source filename



Note: This is < point > < space > < file name >



The file name here takes the correct path



Example: The function in the previous example, you can use the following command:



SOURCE Myfuntions.main











Check load function



Use the SET command to check if the function is loaded. The SET command displays all the load functions in the shell.



Example:








Execute Shell function



To execute a function, simply type in the name of the letter:



Example:








Remove Shell function



Now make some changes to the function. First remove the function so that it is not available to the shell. Use the unset command to complete this function.



The command format is:



unset function_name



Type the set command again, and the function will no longer display



Example:








function parameters



The function can accept parameters:



Pass parameters to the function: when calling a function, separate the given argument list with whitespace after the function name, for example "Testfuncarg1 arg2 ..."



In the function body, you can use $, $, ... Call these parameters; You can also use [email protected], $*, $ #等特殊变量



Example:








function variables



Variable scope:



Environment variables: current shell and child shell are valid



Local variable: Only valid in the current shell process, the dedicated child shell process is started for script execution, so the local variable is scoped to the current shell script file, including the functions in the script.



Local variables: The life cycle of a function; The variable is automatically destroyed at the end of the function



Note: If there are local variables in the function, use local variables if their names are the same as local variables.



Methods for defining local variables in a function



Local Name=value



Example: Defining a different variable








Recursive instances of functions



function recursion:



function calls itself directly or indirectly



Note the number of recursive layers



Recursive instances:



Factorial is an operational symbol invented by Kiston Kaman in 1808 and is a mathematical term



The factorial (factorial) of a positive integer is the product of all positive integers less than and equal to that number, and has a 0 factorial of 1. The factorial writing n! of the natural number N.



N!=1x2x3x...xn.



Factorial can also be defined recursively: 0!=1,n!= (n-1)!xn.



N!=n (n-1) (n-2) ... 1



N (n-1)! = N (n-1) (n-2)!






Analysis with 5 as an example:



First step: 5x (Fact (5-4)) =5x (fact 4)



Step Two: 5x (4XFACT3)



Step Three: 5x (4x (3XFACT2))



Fourth Step: 5x (4x (3x (2XFACT1)))



Since Fact1=1



So 5x4x3x2x1=120








This article is from the "~ Breeze ~" blog, please be sure to keep this source http://weifeng8.blog.51cto.com/1957995/1840963



8.17_linux bash Shell scripting Getting Started (iii) cycle and use of function functions


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.