Shell programming-shell function establishment function library script call work efficiency doubled

Insert picture description here

shell function

Functions can be defined by the user, and then can be called casually in the shell script

Function format

method 1

function 函数名 {
   命令序列
}

Method 2

函数名 () {
   命令序列
}

Insert picture description here
Insert picture description here

Function return value return

  • return means to exit the function and return an exit value, which can be displayed by the $? variable in the script
    • The return value is taken as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
    • The exit status code must be 0-255, the excess value will be divided by 256 to take the remainder
      Insert picture description here
      Insert picture description here
      Insert picture description here

Function parameters

  • In the Shell, that can be passed when calling the function parameters in $1, $2, $3, $4... $#, $*indicating the call back function parameters with
    an outer and function $1, $2... keyboard input value after the call to the script file
  • As shown
    Insert picture description here
    Insert picture description here
  • Example: The value accumulated from 1 to 10 is calculated by passing parameters

Insert picture description here
Insert picture description here

  • Multiply the added value by 2
    by assigning a function
    Insert picture description here

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

Recursion

  • Function calls its own function
  • Factorial example
    Insert picture description here
#分析思路比如输入5时
fact 5
$1=5     temp=4     result=fact 4     echo 5 * (4 * (3 * (2 * (1))))
fact4
$1=4     temp=3     result=fact 3     echo 4 * (fact 3)
fact3
$1=3     temp=2     result=fact 2     echo 3 * (fact 2)
fact2
$1=2     temp=1     result=fact 1     echo 2 * (fact 1)
fact1
1

Recursive directory

Recursively view the directories and files in the /var/log directory
Insert picture description here

Function library

  • The function of the function library: write the functions that implement the same type of function in the same script file for easy classification, and you can call it directly when you use the function

  • Define a simple algorithm function library. The functions in the library are as follows

  • Addition function add

  • Subtraction function

  • Multiplication function

  • Divide function divider
    Insert picture description here

  • Call the function in the function library
    Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_53496398/article/details/114643295