Function programming loop statements and functions

Programming loop statements and functions

Function application example

Example 1

  • Sum two numbers
    1). Define the function through sum(){}
    2). Use the read command to interactively input two numbers and sum them.
    Example 2
  • Write user-defined functions that can be used after logging in to the system
    1). Edit the user-defined function file /root/functiong
    2). Load the executable function file /root/function in the current shell
    3). In ~/.bashrc Add the soure /root/function command to the file

Function scope

  • Functions in Shell scripts are only valid in the current Shell environment
  • The variable in Shell script is global by default
  • Use the local command to limit the variable to the function
  • Example
    1. The internal variables of the function are realized by local
    1). By defining the myfun function, the local variable i is set inside it
    2). The internal and external values ​​of the function are assigned respectively, and the result is verified

Function parameters

  • Usage of parameters
    Function name Parameter 1 Parameter 2 Parameter 3

  • Representation of parameters
    $1 $2 $3 $4

  • Example
    1. Write log information into a file through function parameters
    1). Realize by defining appendfile function

recursive function

  • Call its own function
  • Example
    1. Recursively traverse directories
    1) Realize by defining the recursive function list_files

Shell function

  • Write the sequence of commands together in a format

  • Easy to reuse command sequence

  • Shell function definition
    [function] function name () { command sequence [return x] }


  • How to call the function
    Function name [Parameter 1] [Parameter 2]

Shell array

  • Application scenarios include
    1. Get array length
    2. Get element length
    3. Traverse elements
    4. Element slice
    5. Element replacement
    6. Element deletion

Guess you like

Origin blog.csdn.net/weixin_50346902/article/details/109608994