linux shell script中的函数简介

来源:互联网 发布:淘宝童装轮播图 编辑:程序博客网 时间:2024/05/18 12:34

        懂C语言的人, 没有不知道函数的, 下面我们来看看linux shell script中的函数, 其实也很简单:

[taoge@localhost learn_shell]$ lsa.sh[taoge@localhost learn_shell]$ cat a.sh #! /bin/bashfun(){echo "calling fun"}echo "begin ---"fun   # call funecho "end ---"[taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ ./a.sh begin ---calling funend ---[taoge@localhost learn_shell]$ 
     可以看到, 调用的时候, 不需要写fun(), 而应该用fun, 而且fun函数在定义的时候, 也不需要返回值类型。


     再看:

[taoge@localhost learn_shell]$ lsa.sh[taoge@localhost learn_shell]$ cat a.sh #! /bin/bashfun(){echo $1}echo "begin ---"fun  # call funecho "end ---"[taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ ./a.sh goodbegin ---end ---[taoge@localhost learn_shell]$ 

      可以看到, 调用fun的时候, 没有传递参数, 所以fun中实际并不能访问到$1


     那行, 我们来传一下参数:

[taoge@localhost learn_shell]$ lsa.sh[taoge@localhost learn_shell]$ cat a.sh #! /bin/bashfun(){echo $0echo $1}echo "begin ---"fun "$1"  # call funecho "end ---"[taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ ./a.sh begin ---./a.shend ---[taoge@localhost learn_shell]$ ./a.sh goodbegin ---./a.shgoodend ---

       可见, 参数传递成功。


       最后, 我们来看看return, 注意return 0表示成功:

[taoge@localhost learn_shell]$ lsa.sh[taoge@localhost learn_shell]$ cat a.sh #! /bin/bashfun(){return 0}echo "begin ---"if funthenecho goodelseecho badfiecho "end ---"[taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ [taoge@localhost learn_shell]$ ./a.sh begin ---goodend ---[taoge@localhost learn_shell]$ 


        linux shell script函数就是这么简单, 你想任性一点, 那也可以。






0 0
原创粉丝点击