Chapter 5 Definition, Execution, Parameters and Recursive Functions of Shell Functions

Chapter 5 Definition, Execution, Parameters and Recursive Functions of Shell Functions

Bash (Bourne Again shell) also supports functions. When writing large and complex scripts, functions can be used to write the code into code blocks with relatively independent functions, so that the code module block, the structure is clear, and the code amount of the program is effectively reduced. But the bash shell is an interpreted language, and its execution efficiency is not as high as that of a compiled language.

Definition of shell functions

格式一:(
function name() {
    command sequence (命令序列)
}

格式二:
name() {
    command sequence (命令序列)
}

function execution

[root@ceshi ~]# function name() {
> echo "123"
> }

执行
[root@ceshi ~]# name    #直接调用函数名即可
123

pass parameters

[root@ceshi ~]# vi chuandi.sh
#!/bin/bash
aa="111"    #定义全局变量
bb="222"    #定义全局变量
function name() {           #定义函数名 
        local cc="ccc"      #定义局部变量
        local dd="ddd"      #定义局部变量
        echo $aa, $bb       #打印全局变量
        echo $cc            #打印局部变量
        return 0            #shell函数返回值是正行,并且在0-257之间。
}
echo $dd    #运行局部变量,因为这里是在函数外运行,不会生效。

name    #运行函数name

注意:
$aa是第一个参数$1, $bb是第二个参数$2, 依次类推$n就是第n个参数$n
return 0 参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果作为返回值
执行:
[root@ceshi ~]# /bin/bash chuandi.sh 

111, 222
ccc

recursive function

bash also supports recursive functions (functions that can call themselves)

[root@ceshi ~]# cat digui.sh 
#!/bin/bash
function name() {
        echo $1
        name hello
        sleep 1
}
name

执行脚本会不停的打印hello,按ctrl+c 手动结束

Recursive classic: fork ×××

Many people may have heard of fork×××, it is actually just a very simple recursive program, the program does only the same thing: this recursive function can call itself and continuously generate new processes, which will lead to this Simple procedures quickly exhaust all resources in the system, resulting in a denial of service attack.

.()
{
.|.&
}
;
.
  • Line 1 states that a function is to be defined below, the function name is a decimal point, and there are no optional parameters.
  • Line 2 indicates the start of the function body.
  • Line 3 is what the function body really does. First, it calls this function recursively, then calls a new process using the pipe (what it does is also calls this function recursively), and puts it into the background for execution.
  • Line 4 indicates the end of the function body
  • Line 5 does nothing and is used to separate two commands on the command line. Overall, it shows that this program consists of two parts, first defining a function, and then calling this function.
  • Line 6 means calling this function

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326217786&siteId=291194637