return and exit in bash区别与联系

1. http://blog.sina.com.cn/s/blog_605f5b4f0101b21g.html

2. http://stackoverflow.com/questions/4419952/difference-between-return-and-exit-in-bash-functions

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.

The difference "between the return and exit statement in BASH functions with respect to exit codes" is very little. Both return a status, not values per 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.

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 exectued is returned as the status code (and will be placed in $?).

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 diferent reasons for failure by using status codes.

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

posted @ 2014-06-18 17:41  IT麦兜  阅读(131)  评论(0)    收藏  举报