教程集 www.jiaochengji.com
教程集 >  脚本编程  >  shell  >  正文 Shell脚本使用函数引入文件

Shell脚本使用函数引入文件

发布时间:2014-12-12   编辑:jiaochengji.com
分享下在shell编程中使用函数文件以引入文件的方法,通过实例学习shell函数的编写与调用,有需要的朋友做个参考。

在编写一个较庞大的shell脚本时,可能会涉及许多函数、变量。
这是通常建议将众多的函数、变量放入一个单独的脚本内。

这样做的好处很明显,不用担心某个函数、变量是否已经被定义和使用,也不用频繁地定义、清除函数和变量。
 
一、函数文件的编写
函数文件的格式和脚本文件一样。
[root@jbxue shell]# cat function.example  
 

复制代码 代码示例:

#函数文件中也可以不写下面这行Shell调用语句 
#!/bin/bash 

#function example. 
#This is a function definition script. 
#2013/12/17 
 
hello() 

        echo "Now is the function hello." 
        echo "Hello! $1." 
        return  

 
function hi() 

        echo "Now si the function hi." 
        echo "Hi! $1." 
        return  
}  
 

二、shell函数文件的调用
要调用已经编写好的函数文件,可以像定制工作环境那样,将函数文件包含在脚本文件中,然后直接进行调用。
 
1,下面引入调用函数文件的示例脚本call_func_file.sh。在这个脚本中使用执行的方式调用函数文件,然后再直接调用函数文件中的函数。
[root@jbxue shell]# cat call_func_file.sh  
 

复制代码 代码示例:
#!/bin/bash 
 
#This is a example script. 
#2013/12/17 
 
#function.example 
. ./function.example 
 
#call function hell 
echo "Now call the function hello." 
hello Jhon 
 
#call function hi 
echo "Now call the function hi." 
hi Alix 
 

从以上示例文件中可以看出,调用函数文件的格式为:
. ./function.example  
 
使用这种方式调用函数文件时,函数文件的路径应该与脚本文件的路径相同,否则在调用时应该使用函数文件的绝对路径或相对路径。
 
执行脚本:
 

复制代码 代码示例:
[root@jbxue shell]# ./call_func_file.sh  
Now call the function hello. 
Now is the function hello. 
Hello! Jhon. 
Now call the function hi. 
Now is the function hi. 
Hi! Alix. 
 

2,除了上面介绍的调用方式外,函数文件也可以像变量一样在命令提示符下使用。在命令提示符中调用函数文件后,就可以直接调用函数。
 
在命令提示符中调用函数文件:
 

复制代码 代码示例:
[root@jbxue shell]# . ./function.example  
[root@jbxue shell]# hi Alix 
Now is the function hi. 
Hi! Alix. 
[root@jbxue shell]# hello Alix 
Now is the function hello. 
Hello! Alix. 
 

用户也可以使用上面的方法,将函数文件写入用户的环境变量配置文件中,然后像使用命令一样调用自定义的函数,以实现较复杂的功能。

您可能感兴趣的文章:
Shell脚本使用函数引入文件
python shell是什么
shell编程中的几个小技巧
inux shell初级入门教程
将PHP作为Shell脚本语言使用
linux shell自定义函数与变量作用域
bash shell获取当前正执行脚本的绝对路径
shell特殊变量的含义
深入解析tcsh的初始化配置文件
linux shell中#!bin/sh的理解

关键词: shell函数   
[关闭]
~ ~