16.3.1 自定义函数库

由于Shell是一门面向过程的脚本型语言,而且用户主要是Linux系统管理人员,所以并没有非常活跃的社区,这也造成了Shell缺乏第三方函数库,所以在很多时候需要系统管理人员根据实际工作的需要自行开发函数库。下面建立一个叫lib01.sh的函数库,该函数库目前只有一个函数,用于判断文件是否存在。


  1. [root@localhost ~]# cat lib01.sh

  2. _checkFileExists(){

  3. if [ -f $1 ]; then

  4. echo "File:$1 exists"

  5. else

  6. echo "File:$1 not exist"

  7. fi

  8. }


其他脚本在希望直接调用_checkFileExists函数时,可以通过直接加载lib01.sh函数库的方式实现。加载方式有如下两种:


#

使用“点”命令

[root@localhost ~]# . PATHTO/LIB

#

使用source

命令

[root@localhost ~]# source PATHTO/LIB


假设现在有个脚本想要直接调用_checkFileExists函数,可以通过加载lib01.sh函数库来实现。从下面的演示可以看出,通过调用函数库的方式会使开发脚本变得更为简便。


  1. [root@localhost ~]# cat callLib01.sh

  2. #!/bin/bash

  3. source ./lib01.sh #

  4. 引用当前目录下的lib01.sh

  5. 函数库

  6. _checkFileExists etcnotExistFile #

  7. 调用函数库中的函数

  8. _checkFileExists etcpasswd

  9. #

  10. 执行结果

  11. [root@localhost ~]# bash callLib01.sh

  12. File:etcnotExistFile not exist

  13. File:etcpasswd exists