预计阅读本页时间:-
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:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
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.