函数 : 把一个功能封装起来,使用时直接调用函数名,这样的脚本好处:模块化,代码可读性强,扩展性方便
函数的定义
在shell 中有两种定义函数的语法格式,分别为:
函数名()
{
命令序列
}
或者:
function 函数名()
/function 可以不写
{
命令序列
}
函数的调用
在函数定义好后,用户可以在shell 中直接调用,调用时不用带上()
- 调用语法
函数名 参数1 参数2 ....
- 函数中的变量
均为全局变量,没有局部变量
- 函数的调用
可以传递参数,在函数中用$1,$2, $3...来引用传递的参数。
练习题
例1. 定义example函数,并调用函数
[root@PengFay ~]# vim case1.sh
1 #!/bin/bash
2 abc=123
3 #define function
4 example()
5 {
6 abc=456
7 }
8 echo $abc
9 #调用函数
10 example
11 echo $abc
![](https://i-blog.csdnimg.cn/blog_migrate/40a7f7d3ba8c7bb19ed79aee9febb99e.png)
例2 . 定义delete函数,调用函数
[root@PengFay ~]# vim case3.sh
1 #!/bin/bash
2 delete()
3 {
4 rm -rf $1
5 mkdir $2
6 }
7
8 delete ~/a.txt ~/mydir
例3 . 通过脚本调用其他模块中的函数,编写一个 文件备份db-backup脚本
通常,调用函数是通过
source 命令来调用其他脚本中的函数
首先,定义一个包含不同函数的功能模块
[root@PengFay ~]# vim moudle.sh
1 #!/bin/bash
2 delete()
3 {
4 rm -rf $de
5 }
6 copy()
7 {
8 cp -rf $sdir $tdir
9 }
10 backup()
11 {
12 tar zcvf $tar_name $tar_dir &> /dev/null
13 }
14 quit()
15 {
16 exit
17 }
18
![](https://i-blog.csdnimg.cn/blog_migrate/283ab41d2c81c691c6bd12db553c2563.png)
然后, 编写shell,调用函数
[root@PengFay ~]# vim db-backup.sh
1 #!/bin/bash
2 source /root/moudle.sh /调用 moudle.sh 脚本中的函数
3 while true
4 do
5 cat <<EOF
6 *******************************
7 The following is optional
8 *******************************
9 1) Copy
10 2) Delete
11 3) Backup
12 4) Exit
13 *******************************
14 EOF
15 read -p "please enter your chioce:" option
16 case $option in
17 1)
18 read -p "Please input the file you want to copy:" sdir
19 read -p "Please input the directory you want to copy:" tdir
20 copy
21 ;;
22 2)
23 read -p "Please input your target file:" de
24 delete
25 ;;
26 3)
27 read -p "Please input the backupfile name:" tar_name
28 read -p "Please input the file you want to backup:" tar_dir
29 backup /注意上面这些变量都要和引用函数脚本的变量一致。
30 ;;
31 4)
32 quit;break
33 ;;
34 *)
35 echo "option is inviald."
36 esac
![](https://i-blog.csdnimg.cn/blog_migrate/dad9b2e01ca0836a7c8028d6f1242b89.png)
![](https://i-blog.csdnimg.cn/blog_migrate/02573b0c31b151a44f599b7e81fe8f11.png)