shell 教程六:函数的使用
来源:互联网 发布:淘宝全屏店招导航 编辑:程序博客网 时间:2024/06/03 09:07
1,函数无参无返回值调用
linux@ubuntu:~/test_shell$ cat hello.sh
#!/bin/bash
myFunc(){
echo "myFunc() is called!"
}
echo "begin call myFunc()"
myFunc
echo "end call myFunc()"
linux@ubuntu:~/test_shell$ ./hello.sh
begin call myFunc()
myFunc() is called!
end call myFunc()
2,函数无参有返回值调用
linux@ubuntu:~/test_shell$ cat hello.sh
#!/bin/bash
myFunc(){
echo "myFunc() is called!"
a=1;
b=2;
return $(($a+$b))
}
echo "begin call myFunc()"
myFunc
echo "myFunc() return $?"
echo "end call myFunc()" # 13行与14行代码不能互换,应该echo也是一种函数
linux@ubuntu:~/test_shell$ ./hello.sh
begin call myFunc()
myFunc() is called!
myFunc() return 3
end call myFunc()
注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。
函数返回值在调用该函数后通过 $? 来获得。
3,函数使用参数
linux@ubuntu:~/test_shell$ cat hello.sh
#!/bin/bash
myFunc(){
echo "=====myFunc()===="
echo "$1"
echo "$2"
echo "$3"
echo "$4"
echo "$5"
echo "$6"
echo "$7"
echo "$8"
echo "$9"
echo "${10}" # $10以上的应该要加{},着色也提示了,1与0的颜色不一样,但实测ubuntu是能用的
echo "${11}"
echo "$*"
echo "=====myFunc()===="
a=3
return $a
}
echo "begin call myFunc()"
myFunc 1 2 3 4 5 6 7 8 9 10 11
echo "return1 $?" # return1 与 return2 顺便验证一下上面所说的
echo "return2 $?"
echo "end call myFunc()"
linux@ubuntu:~/test_shell$ ./hello.sh
begin call myFunc()
=====myFunc()====
1
2
3
4
5
6
7
8
9
10
11
1 2 3 4 5 6 7 8 9 10 11
=====myFunc()====
return1 3
return2 0
end call myFunc()
注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。
另外,还有几个特殊字符用来处理参数:
0 0
- shell 教程六:函数的使用
- Shell教程(六):函数、联机帮助
- shell 函数的使用
- shell函数的使用
- shell函数的使用
- shell 函数的使用
- Scrapy Shell的使用教程
- Linux下的shell编程(六)--函数,重定向,文件
- shell中函数的使用
- shell脚本的函数使用
- shell中函数的使用
- Python:Scrapy Shell的使用教程
- shell教程六:多行输入 、调试
- Golang教程:(六)函数
- Shell 学习(六、case...esac的使用和通配符)
- Cognos函数(六) - total的使用
- swift(六)函数的简单使用
- HBase shell使用教程
- ArrayList的equals()方法解析
- Parallels Desktop虚拟的Centos系统设置静态IP连网
- MySQL下“Can’t create/write to file xxx (Errcode: 13)”错误的解决方法
- 模拟表单提交
- Android之定时刷新数据
- shell 教程六:函数的使用
- iOS开发 判断当前APP版本和升级
- zcmu1781
- 移动端页面开发
- 微信企业号 出现redirect_uri unauthorized 50001 解决办法
- Centos6.6设置中文输入法
- 【APP设计利器】Sketch 41 Mac中文破解版(含汉化插件)
- HTML页面后台取静态资源(CSS,JS文件)的路劲问题!
- swift UITextView