Shell script (5)-function format, parameter passing, variables, recursion, function library

One, shell function definition

  • Write the command sequence together in a format to facilitate repeated use of the command sequence

Two, format

1. Format 1:

function 函数名 {
    
    

命令序列

}

2. Format 2:

函数名() {
    
    

命令序列

}

Three, function return value

  • return means to exit the function and return an exit value, which can be displayed by the $? variable in the script

  • Principle of use:

    • 1. Take the return value as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
    • 2. The exit status code must be 0~255, and the value will be divided by 256 when it is exceeded.

Insert picture description here

Insert picture description here
Insert picture description here

Four, function parameter transfer

Insert picture description here
Insert picture description here

Five, the scope of function variables

  • Functions in Shell scripts are only valid in the current Shell environment
  • Variables in Shell scripts are globally effective by default
  • Use the local command to limit the variable to the function

Insert picture description here

Insert picture description here

Insert picture description here
Insert picture description here

Six, recursion

1. Factorial

Insert picture description here

Insert picture description here

2. Recursive search directory

Insert picture description here

Insert picture description here

Seven, create a function library

Put commonly used functions into a separate library script, so that when the script is in use, you can directly call the functions in this library

Insert picture description here

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/Lucien010230/article/details/114641881