zoukankan      html  css  js  c++  java
  • shell脚本--文件包含

      首先介绍一下shell中包含文件的方法,在C,C++,PHP中都是用include来包含文件,Go和Java使用import来包含(导入)包,而在shell中,很简单,只需要一个点“.”,然后跟着文件路径及文件名,或者使用source关键字也可以,注意文件路径可以使用绝对路径和相对路径。

      下面是一个文件包含的例子:three.sh包含one.sh和two.sh

    #!/bin/bash
    #one.sh
    
    one="the is one in file one.sh"
    

      

    #!/bin/bash
    #two.sh
    
    two="this is two in file two.sh"
    

      

    #!/bin/bash
    #three.sh
    
    #以下包含文件的两种方法等效,推荐使用source关键字
    . one.sh 
    source two.sh
    
    echo $one
    echo $two
    

      运行结果:

    [root@localhost ~]# ./three.sh
    the is one in file one.sh
    this is two in file two.sh
    [root@localhost ~]# 
    

      

      需要注意的是,一次只能包含一个文件,不要包含多个文件,比如下例中,尝试使用source一次性包含两个文件,最终,包含进来的只有第一个文件,后面的文件没有成功包含

    #!/bin/bash
    #three.sh
    
    source one.sh two.sh
    
    echo $one
    echo $two
    

      运行结果:

    [root@localhost ~]# ./three.sh
    the is one in file one.sh
    
    [root@localhost ~]# 
    

      

      还要注意的是,在其他语言中,重复包含同一个文件(B包含了A,C包含了A和B,造成C包含了A两次)会报错,而在shell中是不会报错的,仍旧会正常运行!!!!

  • 相关阅读:
    八皇后(回溯经典)
    高精度阶乘(大数运算)
    跳棋(利用规范的数学方法)
    贪心砝码(分治法)
    大数乘方取余
    二分法查找
    汉诺塔(经典递归)(未完全明白)
    斐波那契数列和
    实验 7: OpenDaylight 实验——Python 中的 REST API 调用
    实验 6:OpenDaylight 实验——OpenDaylight 及 Postman 实现流表下发流表
  • 原文地址:https://www.cnblogs.com/-beyond/p/8410583.html
Copyright © 2011-2022 走看看