shell从函数文件中调用函数

碰到一个shell中函数调用的小问题,记录一下。

shell中函数有三种调用方式,一种是在文件前面定义函数,然后在下面直接调用;一种是通过载入shell,在shell中直接调用;第三种是将函数写入文件,然后在其他shell中调用函数。

这里写一下关于第三种方法的例子:

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. is_it_a_directory()  
  2. {  
  3. if [ $# -lt 1 ];then  
  4.   echo "is_it_a_directory:I need an argument"  
  5.   return 1  
  6. fi  
  7.   
  8. _DIRECTORY_NAME=$1  
  9. if [ ! -d $_DIRECTORY_NAME ];then  
  10.   return 1  
  11. else  
  12.   return 0  
  13. fi  
  14. }  
  15.   
  16. error_msg()  
  17. {  
  18. echo -e "\007"  
  19. echo $@  
  20. echo -e "\007"  
  21.   return 0  
  22. }  

这个文件定义了两个函数,我们在下面的shell中调用者两个函数,这里有一点需要注意,在调用之前,要载入函数文件,载入的方式为 . /路径,注意有个空格

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #!/bin/sh  
  2. . functions.sh  
  3. echo -n "enter destination directory :"  
  4. read DIREC  
  5. if is_it_a_directory $DIREC  
  6. then :  
  7. else  
  8.   error_mag "$DIREC does not exist...creating it now"  
  9.   mkdir #DIREC > /dev/null 2>&1  
  10.   if [ $? != 0 ];  
  11.   then  
  12.     error_msg "could not "  
  13.     exit 1  
  14.   else :  
  15.   fi  
  16. fi  
  17.   
  18. echo "extracting files..."  

 

猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/45724117