Bash 函数中 return 和 exit 的区别 [英] Difference between return and exit in Bash functions

查看:53
本文介绍了Bash 函数中 return 和 exit 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bash 函数中的 returnexit 语句在退出代码方面有什么区别?

What is the difference between the return and exit statement in Bash functions with respect to exit codes?

推荐答案

From man bash on return [n];

使函数停止执行并将 n 指定的值返回给其调用者.如果省略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.

... 在 exit [n] 上:

使外壳以 n 状态退出.如果省略 n,则退出状态为执行的最后一个命令的状态.在 shell 终止之前执行 EXIT 上的陷阱.

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.

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

As per your edit of the question, regarding exit codes, return has nothing to do with exit codes. Exit codes are intended for applications/scripts, not functions. So in this regard, the only keyword that sets the exit code of the script (the one that can be caught by the calling program using the $? shell variable) is exit.

编辑 2:

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

My last statement referring exit is causing some comments. It was made to differentiate return and exit for the understanding of the OP, and in fact, at any given point of a program/shell script, exit is the only way of ending the script with an exit code to the calling process.

在 shell 中执行的每个命令都会产生一个本地退出代码":它将 $? 变量设置为该代码,并且可以与 if, 一起使用>&& 和其他运算符来有条件地执行其他命令.

Every command executed in the shell produces a local "exit code": it sets the $? variable to that code, and can be used with if, && and other operators to conditionally execute other commands.

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

These exit codes (and the value of the $? variable) are reset by each command execution.

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

Incidentally, the exit code of the last command executed by the script is used as the exit code of the script itself as seen by the calling process.

最后,函数在调用时充当与退出代码相关的 shell 命令.函数的退出代码(函数内)使用return设置.因此,当在函数 return 0 中运行时,函数执行终止,给出退出代码 0.

Finally, functions, when called, act as shell commands with respect to exit codes. The exit code of the function (within the function) is set by using return. So when in a function return 0 is run, the function execution terminates, giving an exit code of 0.

这篇关于Bash 函数中 return 和 exit 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆