码迷,mamicode.com
首页 > 系统相关 > 详细

shell学习——关于shell函数库的使用

时间:2019-09-05 11:59:33      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:test   exit   shell函数   一个   ons   技术   div   学习   包含   

shell函数库的理解:

  个人理解,shell函数库实质为一个脚本,脚本内包含了多个函数(函数具有普遍适用性)。

shell函数库的调用:

  通过  . /path/lib/file.lib 或者 source /path/lib/file.lib的方式加载,然后正常函数方式调用。

示例如下:

  创建函数库文件:libMyfunctions.sh

#!/bin/bash

#创建一个函数库文件,用来打印$PATH的路径

showPATH(){
        oldifs="$IFS"
        IFS=:
        for dir in $PATH 
        do
                echo $dir
        done

        IFS="$oldifs"
}
#这里可以增加N个其他函数

  调用函数库文件:

#!/bin/bash
#方法1:
#. /home/wyf349/user/lib/libMyfunctions.sh     
#通过 . 加载函数库文件,注意 . 和路径之间存在一个空格
#方法2: source ../lib/libMyfunctions.sh showPATH

  需要注意的是,函数库的加载,其实是在调用的脚本中执行了这个文件,所以在函数库文件中不能包含exit的语句,否则将导致当前实例退出。

使用Ubuntu的时候,可能存在如下提示:

wyf349@ubuntu:~/user/study_shell$ sh lib_stduy_test1.sh*
lib_stduy_test1.sh: 7: lib_stduy_test1.sh: source: not found
lib_stduy_test1.sh: 9: lib_stduy_test1.sh: add: not found

  原因为:Ubuntu默认的sh解析器为dash,需要调整为bash

ls -l /bin/sh
#如果输出为dash
sudo dpkg-reconfigure dash 
#在弹出的选择框中,选择no即可

  

 

技术图片

 

shell学习——关于shell函数库的使用

标签:test   exit   shell函数   一个   ons   技术   div   学习   包含   

原文地址:https://www.cnblogs.com/wyf-349/p/11464975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!