Shell script strategy-function application (return value, parameter passing, variable scope, recursion and function library)


I. Overview

  • Shell function is also often used by us, because some command sequences need to be called and executed repeatedly. If you use the same command to write it again every time, it will result in a large amount of code and a large number of lines.
  • To solve this problem, the command sequence can be written together in a format so that it can be reused
  • Therefore, the essence of the Shell function is a reusable script code. This code has been written in advance and placed in a designated location. It can be called directly when used.

2. Format definition

  • [function] is optional, indicating the function of the function, this can be omitted
  • The function name is followed by a (), there is no content inside
  • And the sequence of commands we execute is placed in {}
  • If sometimes we call a lot of functions, then we can write several at once
  • The format is as follows:
#格式一:

function 函数名 {
    
    
        命令序列
}


#格式二:

函数名() {
    
    
        命令序列
}


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:
    • 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, and the value will be divided by 256 if it exceeds
  • Example 1:
[root@localhost sh]# vim xc1.sh

#!/bin/bash

function xcf {
    
    
        read -p "请输入:" a
        a=$[$a*2]
        return $a
}

xcf
echo $?

mark

  • Example 2:
[root@localhost sh]# vim xc2.sh

#!/bin/bash

xcf() {
    
    
read -p "请输入:" a
        a=$[$a*2]
        echo $a

}

result=`xcf`
echo $result        ##建议把值放入变量,方便以后调用

mark

supplement:

  • Following {} is the "main command", the first to be executed is this
  • After calling the function name, the code in the above command sequence will be executed

Four, function parameter transfer

  • As the name implies, passing parameters is passing parameters
  • We have learned position variables before , so I won’t repeat them here
  • Examples are as follows:
[root@localhost sh]# vim xc3.sh

#!/bin/bash

sum() {
    
    

xcf=$[$1 + $2]
echo $xcf

}

read -p "输入第一个参数:" first
read -p "输入第二个参数:" second

sum $first $second        ##调用函数,传第一个以及第二个输入的值,传参给$1以及$2

mark

  • Another more convenient way
  • And I think this way is easier to understand
    mark
    mark
  • The former method is more humane, but for us professionals, the latter method is often used more quickly and efficiently.
  • More high-end application scenarios often do not need so much "humanization", they are all automated

Five, the scope of function variables

  • Functions in Shell scripts are only valid in the current Shell environment
  • Variables in Shell scripts are global by default
  • Use the local command to limit the variable to the function
  • Examples are as follows:
[root@localhost opt]# vim xc1.sh

#!/bin/bash

zxc() {
    
    

a=5
b=6
echo "c等于$c"
}

a=8
c=9
zxc
echo "a等于$a"
echo "b等于$b"
  • As you can see, the c defined in the main command is also valid in the function
  • Why output c first, pay attention to the order in the main command, first define a and c, then the function zxc, and re-define a and b in the function zxc, overwriting the original definition, and then under zxc The output of a and b, so the sequence is as follows:
[root@localhost opt]# ./xc1.sh 
c等于9
a等于5
b等于6
  • If we want to confine the values ​​defined by the function to the function, we need to use local
  • Variables that only take effect in functions are also called local variables . The following is an example:
[root@localhost opt]# vim xc2.sh

#!/bin/bash

zxc() {
    
    
local i
i=8
echo "inside $i"

}

i=9
zxc
echo "outside $i"
  • Inside and outside are used to distinguish, easy to identify and understand
  • First define i=9, then output the function zxc, define i=8 in the function, and output inside 8. Because local is added here, the 8 defined in the function is only valid in the function, and the $i outside the function is still 9 defined at the beginning
[root@localhost opt]# chmod +x xc2.sh 
[root@localhost opt]# ./xc2.sh 
inside 8
outside 9
  • Let's further deepen the impression
    mark
    mark
  • Local variables and global variables are two different variables, which can be assigned different values, and they can have the same name. See the example below to explain
    mark
    mark

Six, recursion

  • Functions directly or indirectly call their own functions
  • Not much to say, start showing

1. Factorial

Popular science

  • Factorial is an arithmetic symbol invented by Keston Kaman in 1808. It is a mathematical term
  • The factorial of a positive integer is the product of all positive integers less than or equal to the number , and the factorial of 0 is 1.
自然数n的阶乘写作n!  
n!=1×2×3×…×n

阶乘亦可以递归方式定义:  
0!=1,n!=(n-1)!×n  
n!=n(n-1)(n-2)…1

Demo

mark
mark

2. Recursive directory

  • The essence of recursion:
    • Since when
    • When will it end
    • What does each recursion need to do
  • Examples are as follows:
  • Traverse all files under /var/log
[root@localhost opt]# vim xc4.sh

#!/bin/bash

function list_files {
    
    
##定义递归遍历目录的函数
for f in `ls $1`
##循环遍历目录
do
        if [ -d "$1/$f" ]
        then
        ##判断若为目录则按格式输出目录名称并继续调用函数遍历这个目录
                echo "$2$f"
                list_files "$1/$f" "$2"
        else
        ##判断若为文件则直接按照格式输出文件名称
                echo "$2$f"
        fi
done
}

list_files "/var/log" ""
##调用函数,第一个参数为要进行遍历的目录,第二个参数为格式设定,区分目录层级
  • Test one
[root@localhost opt]# ./xc4.sh 
anaconda
anaconda.log
ifcfg.log
journal.log
ks-script-1_XapN.log
ks-script-b5hX60.log
packaging.log
program.log
storage.log
syslog
X.log
audit
audit.log
boot.log
boot.log-20201222
.
..
...
....
.....略

Seven, create a function library

The function library only contains the definition of the function, and the script contains both the definition of the function and the executable code

  • Define a function library, which implements the following functions
    • Addition function
    • Subtraction function
    • Multiplication function
    • Division function
  • First define the basic function library file
[root@localhost opt]# vim xc5.sh

#!/bin/bash

jiafa () {
    
    
        result=$[$1 + $2]
        echo $result
}

jianfa () {
    
    
        result=$[$1 - $2]
        echo $result
}

chengfa () {
    
    
        result=$[$1 * $2]
        echo $result
}

chufa () {
    
    
if [ $2 -ne 0 ]
        then
                result=$[$1 / $2]
                echo $result
        else
                echo "$2不能等于0!"
fi
}

  • Define script
[root@localhost opt]# vim xc6.sh

#!/bin/bash

. /opt/xc5.sh        ##引入函数库文件

read -p "输入第一个参数值:" first
read -p "输入第二个参数值:" second

result1=`jiafa $first $second`
result2=`jianfa $first $second`
result3=$(chengfa $first $second)
result4=$(chufa $first $second)

echo $result1
echo $result2
echo $result3
echo $result4
  • Test one
    mark

Guess you like

Origin blog.csdn.net/weixin_51486343/article/details/111568761