加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash函数中返回和退出之间的区别

发布时间:2020-12-16 01:40:31 所属栏目:安全 来源:网络整理
导读:Bash函数中的return和exit语句与退出代码有什么区别? 解决方法 来自man bash返回[n]; Causes a function to stop executing and return the value specified by n to its caller. If n is omitted,the return status is that of the last command executed
Bash函数中的return和exit语句与退出代码有什么区别?

解决方法

来自man bash返回[n];

Causes a function to stop executing and return the value specified by n to its caller. If n is omitted,the return status is that of the last command executed in the function body.

…退出[n]:

Cause the shell to exit with a status of n. If n is omitted,the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

编辑:

根据您对问题的编辑,关于退出代码,返回与退出代码无关.退出代码用于应用程序/脚本,而不是函数.因此,在这方面,唯一设置脚本退出代码的关键字(可以使用$?shell变量由调用程序捕获的那个)是exit.

编辑2:

我最后一条引用退出的声明引起了一些评论.它是为了区分返回和退出以理解OP,事实上,在程序/ shell脚本的任何给定点,exit是使用退出代码结束脚本到调用进程的唯一方法.

在shell中执行的每个命令都会生成一个本地“退出代码”:它设置$?变量到该代码,可以与if,&&和其他运算符有条件地执行其他命令.

每个命令执行都会重置这些退出代码(以及$?变量的值).

顺便提一下,脚本执行的最后一个命令的退出代码被用作调用进程看到的脚本本身的退出代码.

最后,函数在被调用时,作为退出代码的shell命令.函数的退出代码(在函数内)使用return设置.因此,当函数返回0运行时,函数执行终止,退出代码为0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读