Returning Values from Bash Functions

Source: Internet
Author: User

Bash functions, unlike functions in most programming languages does not allow you to return a value to

The caller. When a bash function ends It return value is it Status:zero for success, Non-zero for failure. To

Return values, can set a global variable with the result, or use command substitution, or you can pass in

The name of a variableto use as the result variable. The examples below describe these different mechanisms.

  Although Bash have a return statement, the only thing you can specify with it is the function ' s status, which

is a numeric value as the value specified in an exit statement. The status value is stored in the $? Variable. If

A function does not contain a return statement, it status is set based on the status of the last statement executed

In the function. To actually return arbitrary values to the caller you must use other mechanisms.

The simplest-return a value from a bash function was to just set a global variable to the result. Since

All variables in bash be global by default this is easy:

function MyFunc () {Myresult='some value'}myfunc Echo $myresult

The code above sets the global variable Myresult to the function result. Reasonably simple, but as we all

know, using global variables, particularly in large programs, can leads to difficult to find bugs.

A better approach is to use the local variables in your functions. The problem then becomes how does you get

The result to the caller. One mechanism is to use command substitution:

function MyFunc () {local Myresult='some value'echo'$myresult  "}result=$ (myfunc)echo $result  

Here the result was output to the STDOUT and the Caller uses command substitution to capture the value

In a variable. The variable can then be used as needed.

Excerpt from:

Returning Values from Bash functions:http://www.linuxjournal.com/content/return-values-bash-functions

Returning Values from Bash Functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.