第三章、shell语法 函数 和 exit 命令
2022/7/10 5:20:02
本文主要是介绍第三章、shell语法 函数 和 exit 命令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
第三章、shell语法 函数 和 exit 命令
函数
shell
中的函数和 c/c++
中的函数类似,但是在函数输出和返回值方面有些许的不同。
函数return
返回值: 函数返回的是 exit code
,可以通过 $?
变量获取。
函数输出: 函数中 echo
的字符查,在stdout
中,可以通过$(function_name 参数)
获取
函数返回值exit code
和输出output
函数定义
[function] function_name() { # function关键字可以省略 sentence1 sentence2 return exit_code # 不指定 exit_code 时候,默认为 0,可以直接写 return,或者是连 return 也不写 }
函数不获取 exit code 和 output
#! /bin/bash function test1() { if [ $1 -eq 0 ] then echo "\$1 == 0" return 0 else echo "\$1 != 0" return 155 fi } test1 2 echo $?
输出
$1 != 0 155
函数获取 exit code 和 output
#! /bin/bash function test1() { if [ $1 -eq 0 ] then echo "\$1 == 0" return 0 else echo "\$1 != 0" return 155 fi } output=$(test1 2) exit_code=$? echo "output=${output}" echo "exit_code=${exit_code}"
输出
output=$1 != 0 exit_code=155
函数参数
函数参数的传递
函数中 $0
表示文件名,注意是文件名,不是函数名
$1
、$2
这些仍是位置参数。
我们在上面的例子中,已经有过使用。
现在让我们递归计算 0 + 1 + 2 + ... + $1
首先想,需要使用 echo
,因为返回值只能是 0-255
function dfs() { if [ $1 -eq 0 ] then echo 0 return 0 else pre_output=$(dfs `expr $1 - 1`) echo "`expr ${pre_output} + $1`" return 0 fi } res=$(dfs 10) echo $res
输出
55
函数局部变量
#! /bin/bash function func() { local name='xyg' echo "inside ${name}" return 0 } func echo "outside ${name}"
输出
inside xyg outside
倘若不定义局部变量
#! /bin/bash function func() { name='xyg' echo "inside ${name}" return 0 } func echo "outside ${name}"
输出:
inside xyg outside xyg
注意和 export 区分,export全局变量是 子进程也可以使用!
exit 命令
之前函数,关键字return
是用于退出函数,并指定exit_code
默认为0。
在脚本bash
中存在关键字exit exit_code
,来退出当前shell进程,并返回一个退出状态;同样是使用$?
可以接收这个退出状态。
可以接受一个整数值(0-255)作为参数,代表退出状态。如果不指定,默认状态值是 0。所有的返回状态中,只有0
表示正常退出。
脚本事例
#! /bin/bash if [ $# -eq 3 ] # 位置参数数量 = 3,才是合法 then echo "legal arguments" exit 0 else echo "illegal arguments" exit 1 fi
输出
(base) xyg@vivo-xyg:~/xyg/test$ ./test.sh # 没有参数,illegal illegal arguments (base) xyg@vivo-xyg:~/xyg/test$ echo $? 1 (base) xyg@vivo-xyg:~/xyg/test$ ./test.sh 1 2 # 两个参数 illegal illegal arguments (base) xyg@vivo-xyg:~/xyg/test$ echo $? 1 (base) xyg@vivo-xyg:~/xyg/test$ ./test.sh 1 2 3 # 三个参数 legal legal arguments (base) xyg@vivo-xyg:~/xyg/test$ echo $? 0
参考文献
强烈推荐 Y总的基础课
linux教程-孟庆昌
这篇关于第三章、shell语法 函数 和 exit 命令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?