第98页 | Learning the Bash Shell | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

Return

The second feature we need is the statement return N, which causes the surrounding function to exit with exit status N. N is actually optional; it defaults to the exit status of the last command. Functions that finish without a return statement (i.e., every one we have seen so far) return whatever the last statement returns. return can only be used inside functions, and shell scripts that have been executed with source. In contrast, the statement exit N exits the entire script, no matter how deeply you are nested in functions.

Getting back to our example: if the call to the built-in cd were last in our cd function, it would behave properly. Unfortunately, we really need the assignment statement where it is. Therefore we need to save cd's exit status and return it as the function's exit status. Here is how to do it:

cd ( )
{
    builtin cd "$@"
    es=$?
    echo "$OLDPWD --> $PWD"
    return $es
}

The second line saves the exit status of cd in the variable es; the fourth returns it as the function's exit status. We'll see a substantial cd "wrapper" in Chapter 7.

Exit statuses aren't very useful for anything other than their intended purpose. In particular, you may be tempted to use them as "return values" of functions, as you would with functions in C or Pascal. That won't work; you should use variables or command substitution instead to simulate this effect.

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库