博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux shell script中的函数简介
阅读量:4142 次
发布时间:2019-05-25

本文共 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/

你可能感兴趣的文章
为什么说程序员是“培训班出来的”就是鄙视呢?
查看>>
码农吐糟同事:写代码低调点不行么?空格回车键与你有仇吗?
查看>>
阿里p8程序员四年提交6000次代码的确有功,但一次错误让人唏嘘!
查看>>
一道技术问题引起的遐想,最后得出结论技术的本质是多么的朴实!
查看>>
985硕士:非科班自学编程感觉还不如培训班出来的,硕士白读了?
查看>>
你准备写代码到多少岁?程序员们是这么回答的!
查看>>
码农:和产品对一天需求,产品经理的需求是对完了,可我代码呢?
查看>>
程序员过年回家该怎么给亲戚朋友解释自己的职业?
查看>>
技术架构师的日常工作是什么?网友:搭框架,写公共方法?
查看>>
第四章 微信飞机大战
查看>>
九度:题目1008:最短路径问题
查看>>
九度Online Judge
查看>>
九度:题目1027:欧拉回路
查看>>
九度:题目1012:畅通工程
查看>>
九度:题目1017:还是畅通工程
查看>>
九度:题目1034:寻找大富翁
查看>>
第六章 背包问题——01背包
查看>>
第七章 背包问题——完全背包
查看>>
51nod 分类
查看>>
1136 . 欧拉函数
查看>>