当前位置:网站首页>Shell编程-函数
Shell编程-函数
2022-07-21 11:26:00 【悟红尘】
Shell中的函数分为两种,一种是系统函数,一种是自定义函数
系统函数: basename,获取最后的文件名,如果第二个参数加上后缀就会去掉后缀
[root@VM_0_11_centos shell]# basename /root/training/shell/shell_for.sh
shell_for.sh
[root@VM_0_11_centos shell]# basename /root/training/shell/shell_for.sh .sh
shell_for
系统函数: dirname 跟basename正好相反,返回的是初文件名以外的目录
[root@VM_0_11_centos shell]# dirname /root/training/shell/shell_for.sh
/root/training/shell
自定义函数:
自定义函数的各式如下:
[function] functionName [()] {
具体逻辑
[return int]
}
中括号里面的都是选的,也就是说可以不加,function可以不加,甚至函数名后面的括号也可以不加,但是要注意空格,返回值也可以不加,如果不加则默认是最后一条语句的结果作为返回值,return后面跟的是数值
调用的话直接functionName即可
怎么传参数呢?函数名括号后面是没有参数的。实际上传的时候直接在跟在调用的命令后面,函数体里面回去参数使用$n,记得在上几篇说过一个知识点$n可以获取命令行的参数,这里跟那里是一样的。$1表示第一个参数,$2表示第二个参数,依次类推,10之后用${10}.
比如:
getSum () {
SUM=$[$1+$2]
echo "sum = $SUM"
return $SUM
}
getSum 10 20
echo $?
结果:
[root@VM_0_11_centos shell]# ./shell_fun.sh
sum = 30
30
上面有一个$?,这个操作符是预定义变量表示的最后的执行状态,这个前面也说过,还有两个$$表示当前进程的pid,$!表示的是最后一个后台进程的pid。
未完待续!
欢迎关注我的公众号:北风中独行的蜗牛
参考:
https://www.runoob.com/linux/linux-shell-func.html
边栏推荐
- Ansvc reactive power compensation device helps an environmental protection energy project in Jiangsu
- Code management (novice)
- Design and application of prepaid platform on power reform policy
- 5.2访问控制
- Application of SCA on devsecops platform
- 做做C#
- Application of DC distribution system products at the end of data center
- 静态方法与实例方法的区别
- 解决ssh登录后闲置时间过长而断开连接
- Integer
猜你喜欢
百度副总裁李硕:AI能深入场景创造真价值,从传感器到大屏仅是数字化开始...
When idea creates a folder, the empty folder of the folder expands and overlaps
Li Shuo, vice president of Baidu: AI can go deep into the scene and create real value. From sensors to large screens, it is just the beginning of digitalization
Field injection is not recommended
[mid 2022 summary] I walk very slowly, but I never retreat
第三章课后习题15-23
servlet写webapp时,用filter拦截实现登陆验证
50个名额限量开放|带着OceanBase年度发布会的消息走来了!
Flink使用api执行sql的时候报错
静态方法与实例方法的区别
随机推荐
50个名额限量开放|带着OceanBase年度发布会的消息走来了!
Local inner class
BUUCTF-pwn[1]
MySQL索引原理以及查询优化「建议收藏」
How to build a good knowledge base management system?
秒杀设计
Idea建文件夾時,文件夾的空文件夾的展開與重疊
MySQL终章
zooInspector下载
MySQL 5.7.9版本sql_mode=only_full_group_by问题
A trick to teach you how to master online videos
PWN的学习
Converter
3.1栈
局部内部类
Abstract class name as formal parameter and return value
抽象类名作为形参和返回值
Monai label installation process and use strategy
JS部分
百度副总裁李硕:AI能深入场景创造真价值,从传感器到大屏仅是数字化开始...