在bash函数的返回和退出之间的区别 [英] Difference between return and exit in BASH functions
问题描述
是什么收益之间的差异
和退出
声明BASH功能就退出codeS ?
What is the difference between the return
and exit
statement in BASH functions with respect to exit codes?
推荐答案
收益
返回从函数的值。 退出
放弃当前的shell。
return
returns a value from a function. exit
abandons the current shell.
编辑:
根据你的问题的编辑,对于出口codeS,收益
无关,退出codeS。退出codeS旨在用于应用程序/脚本,而不是函数。所以在这方面,设置了脚本的退出code(可以使用 $?
shell变量调用程序被抓的)中的唯一关键字为退出
。
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:
我最后的发言中提及退出
会引起一些评论。这是为了区分收益
和退出
的OP的理解,而事实上,在的的给定程序/ shell脚本点,退出
是结束与退出code到调用进程脚本的唯一途径。
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执行的每个命令产生一个本地的退出code:它集 $
变量为code,并且可以使用?与如果
,&放大器;&安培;
等运营商有条件地执行其他命令
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.
这些退出codeS(和 $?
变量的值)是由每个命令执行复位。
These exit codes (and the value of the $?
variable) are reset by each command execution.
顺便说一下,由脚本执行的最后一个命令的退出code作为脚本本身调用进程所看到的退出code。
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命令就退出codeS。该函数的退出code(在的功能),通过使用收益
设置。因此,当在一个函数返回0
运行,功能执行结束,给人的0退出code。
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函数的返回和退出之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!