Bash 函数中 return 和 exit 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4419952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:56:58  来源:igfitidea点击:

Difference between return and exit in Bash functions

bashfunctionreturn-valuereturnexit

提问by lecodesportif

What is the difference between the returnand exitstatement in Bash functions with respect to exit codes?

Bash 函数中的returnandexit语句与退出代码有什么区别?

采纳答案by Diego Sevilla

From man bashon return [n];

man bashreturn [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 指定的值返回给其调用者。如果省略 n,则返回状态为函数体中执行的最后一个命令的状态。

... on exit [n]:

...在exit [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 以 n 状态退出。如果省略 n,则退出状态是执行的最后一个命令的状态。在 shell 终止之前执行 EXIT 上的陷阱。

EDIT:

编辑:

As per your edit of the question, regarding exit codes, returnhas 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.

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

EDIT 2:

编辑2:

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

我的最后一个陈述exit引起了一些评论。它是为了区分returnexit理解 OP,事实上,在程序/shell 脚本的任何给定点,exit都是以调用进程的退出代码结束脚本的唯一方法。

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.

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

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.

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

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

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

回答by SiegeX

returnwill cause the current function to go out of scope, while exitwill cause the script to end at the point where it is called. Here is a sample program to help explain this:

return将导致当前函数超出范围,同时exit将导致脚本在调用它的地方结束。这是一个示例程序来帮助解释这一点:

#!/bin/bash

retfunc()
{
    echo "this is retfunc()"
    return 1
}

exitfunc()
{
    echo "this is exitfunc()"
    exit 1
}

retfunc
echo "We are still here"
exitfunc
echo "We will never see this"

Output

输出

$ ./test.sh
this is retfunc()
We are still here
this is exitfunc()

回答by Mike Q

I don't think anyone has really fully answered the question because they don't describe how the two are used. OK I think we know that exit kills the script, where ever it is called and you can assign a status to it as well such as exit or exit 0 or exit 7 and so forth. This can be used to determine how the script was forced to stop if called by another script etc. Enough on exit.

我认为没有人真正完全回答了这个问题,因为他们没有描述如何使用这两者。好的,我想我们知道 exit 会杀死脚本,无论在何处调用它,您都可以为其分配状态,例如 exit 或 exit 0 或 exit 7 等等。这可用于确定脚本在被另一个脚本等调用时如何强制停止。退出时足够了。

return when called will return the value specified to indicate the function's behavior, usually a 1 or a 0. For example:

调用时返回将返回指定的值以指示函数的行为,通常是 1 或 0。例如:

    #!/bin/bash
    isdirectory() {
      if [ -d "" ]
      then
        return 0
      else
        return 1
      fi
    echo "you will not see anything after the return like this text"
    }

check like this:

像这样检查:

    if isdirectory ; then echo "is directory"; else echo "not a directory"; fi

or like this:

或者像这样:

    isdirectory || echo "not a directory"

In this example, the test can be used to indicate if the directory was found. notice that anything after the return will not be executed in the function. 0 is true but false is 1 in the shell, different from other prog langs.

在此示例中,测试可用于指示是否找到了目录。请注意,返回之后的任何内容都不会在函数中执行。0 为真,但在 shell 中为 1,与其他编语言不同。

For more info on functions: http://www.linuxjournal.com/content/return-values-bash-functions

有关函数的更多信息:http: //www.linuxjournal.com/content/return-values-bash-functions

NOTE: The isdirectory function is for instructional purposes only. This should not be how you perform such an option in a real script.

注意: isdirectory 函数仅用于教学目的。这不应该是您在真实脚本中执行此类选项的方式。

回答by user2100135

Remember, functions are internal to a script and normally return from whence they were called by using the return statement. Calling an external script is another matter entirely, and scripts usually terminate with an exit statement.

请记住,函数是脚本内部的,通常使用 return 语句从调用它们的地方返回。调用外部脚本完全是另一回事,脚本通常以 exit 语句终止。

The difference "between the return and exit statement in BASH functions with respect to exit codes" is very little. Both return a status, not valuesper se. A status of zero indicates success, while any other status (1 to 255) indicates a failure. The return statement will return to the script from where it was called, while the exit statement will end the entire script from whereever it is encountered.

“关于退出代码的 BASH 函数中的 return 和 exit 语句之间的差异”非常小。两者都返回一个状态,而不是本身。状态为零表示成功,而任何其他状态(1 到 255)表示失败。return 语句将从它被调用的地方返回到脚本,而 exit 语句将从遇到它的任何地方结束整个脚本。

return 0  # returns to where the function was called.  $? contains 0 (success).

return 1  # returns to where the function was called.  $? contains 1 (failure).

exit 0  # exits the script completely.  $? contains 0 (success).

exit 1  # exits the script completely.  $? contains 1 (failure).

If your function simply ends with no return statement, the status of the last command executed is returned as the status code (and will be placed in $?).

如果您的函数只是以没有 return 语句结束,则最后执行的命令的状态将作为状态代码返回(并将放置在 中$?)。

Remember, return and exit give back a status code from 0 to 255, available in $?. You cannot stuff anything else into a status code (e.g. return "cat"); it will not work. But, a script can pass back 255 different reasons for failure by using status codes.

请记住,return 和 exit 返回一个从 0 到 255 的状态代码,在$?. 您不能在状态代码中填充任何其他内容(例如,返回“cat”);不起作用。但是,脚本可以通过使用状态代码传递 255 个不同的失败原因。

You can set variables contained in the calling script, or echo results in the function and use command substitution in the calling script; but the purpose of return and exit are to pass status codes, not values or computation results as one might expect in a programming language like C.

您可以设置调用脚本中包含的变量,或者在函数中回显结果并在调用脚本中使用命令替换;但是 return 和 exit 的目的是传递状态代码,而不是像 C 这样的编程语言中可能期望的值或计算结果。

回答by Juraj

Sometimes, you run a script using .or source.

有时,您使用.或运行脚本source

. a.sh

If you include an exitin the a.sh, it will not just terminate the script, but end your shell session.

如果您exit在 中包含a.sh,它不仅会终止脚本,还会结束您的 shell 会话。

If you include a returnin the a.sh, it simply stops processing the script.

如果包含returna.sh,它只是停止处理脚本。

回答by Jyo the Whiff

In simple words (mainly for newbie in coding), we can say,

简单来说(主要针对编码新手),我们可以说,

`return` : exits the function,
`exit()` : exits the program(called as process while running)

Also If you observed, this is very basic but...,

此外,如果您观察到,这是非常基本的,但是...,

`return` : is the keyword
`exit()` : is the function

回答by fcm

  • exitterminate the current process; with or without exit code, consider this a system more than a program function. Note that when sourcing, exitwill end the shell, however, when running will just exitthe script.

  • returnfrom a function go back to the instruction after the call, with or without a return code. returnis optional and it's implicit at the end of the function. returncan only be used inside a function.

  • exit终止当前进程;有或没有退出代码,将其视为一个系统而不是程序功能。请注意,在采购时,exit将结束 shell,但是,在运行时将只是exit脚本。

  • return从函数返回调用后的指令,带或不带返回码。return是可选的,它在函数的末尾是隐式的。return只能在函数内部使用。

I want to add that while being sourced, it's not easy to exitthe script from within a function without killing the shell. I think, an example is better on a 'test' script

我想补充一点,在获取源代码时,exit在不杀死 shell 的情况下从函数内部编写脚本并不容易。我认为,一个例子在“测试”脚本上更好

#!/bin/bash
function die(){
   echo ${1:=Something terrible wrong happen}
   #... clean your trash
   exit 1
}

[ -f /whatever/ ] || die "whatever is not available"
# now we can proceed
echo "continue"

doing the following:

执行以下操作:

user$ ./test
Whatever is not available
user$

test-and- the shell will close.

test-并且-外壳将关闭。

user$ . ./test
Whatever is not available

only testwill finish and the prompt will show.

只会test完成并显示提示。

The solution is to enclose the potentially procedure in (and )

解决方案是将潜在的程序包含在()

#!/bin/bash
function die(){
   echo $(1:=Something terrible wrong happen)
   #... clean your trash
   exit 1
}

( # added        
    [ -f /whatever/ ] || die "whatever is not available"
    # now we can proceed
    echo "continue"
) # added

now, in both case only testwill exit.

现在,在这两种情况下都只会test退出。

回答by Craig Hicks

The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?

OP 的问题:BASH 函数中的 return 和 exit 语句在退出代码方面有什么区别?

Firtly, some clarification is required:

首先,需要澄清一下:

  • A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.
  • A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $? which always has a numeric value. It is a special variable that cannot be set like "?=1", but is set only in special ways (see below *). The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called functions code.
  • 不需要 (return|exit) 语句来终止 (function|shell) 的执行。即使没有 (return|exit) 语句, (function|shell) 也会在到达其代码列表的末尾时终止。
  • (return|exit) 语句不需要从终止的 (function|shell) 传回值。每个进程都有一个内置变量 $? 它总是有一个数值。它是一个特殊的变量,不能像“?=1”那样设置,只能以特殊的方式设置(见下文*)。$的价值?在(被调用的函数|子shell)中执行的最后一个命令之后是传回(函数调用者|父shell)的值。无论最后执行的命令是 ("return [n]"| "exit [n]") 还是普通命令(“return”或其他恰好是被调用函数代码中的最后一个命令),都是如此。

In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions & return or shells & exit respectively.

在上面的项目符号列表中,从“(x|y)”中选择始终是第一项或始终是第二项,以分别获取有关函数和返回或外壳和退出的语句。

What is clear is that they both share common usage of the special variable $? to pass values upwards after they terminate.

很明显,它们都共享特殊变量 $ 的共同用法?在它们终止后向上传递值。

* Now for the special ways that $? can be set:

* 现在对于 $ 的特殊方式?可以设置:

  • When a called function terminates and returns to it's caller then $? in the caller will be equal to the final value of $? in the terminated function.
  • When a parent shell impliciltly or explicitly waits on a single sub shell and is released by termination of that sub shell, then $? in the parent shell will be equal to the final value of $? in the terminated sub shell.
  • Some built-in functions can modify $? depending upon their result. But some don't.
  • Built-in functions "return" and "exit", when followed by a numerical argument both $? with argument, and terminate execution.
  • 当被调用的函数终止并返回给它的调用者时, $? 在调用者中将等于 $ 的最终值?在终止的函数中。
  • 当父 shell 隐式或显式等待单个子 shell 并通过该子 shell 的终止而释放时,则 $? 在父 shell 中将等于 $? 在终止的子外壳中。
  • 一些内置函数可以修改 $? 取决于他们的结果。但有些人没有。
  • 内置函数“return”和“exit”,当后面跟着一个数字参数 $? 带参数,并终止执行。

It is worth noting that $? can be assigned a value by calling exit in a sub shell, like this:

值得注意的是,$? 可以通过在子 shell 中调用 exit 来赋值,如下所示:

# (exit 259)
# echo $?
3  

回答by Ahmad Awais

First of all, returnis a keyword and exitmy friend is a function.

首先,return是一个关键字,exit我的朋友是一个函数。

That said, here's a simplest of explanations.

也就是说,这是一个最简单的解释。

returnIt returns a value from a function.

return它从函数返回一个值。

exitIt exits out of or abandons the current shell.

exit它退出或放弃当前外壳。