本文共 1678 字,大约阅读时间需要 5 分钟。
懂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 $0 echo $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 funthen echo goodelse echo 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函数就是这么简单, 你想任性一点, 那也可以。
转载地址:http://hfgvi.baihongyu.com/