1

Shell functions are just statements and they don't return values. Can anyone share best practice on writing functions that return values in bash?

Let's say I've a function that joins two strings:

JoinStrings() {
    returnValue="$1$2"
}

How do I reuse this function in my code? How do I get returnValue to be returned to caller? Should I just use it as a global after this function call? That leads to many errors with global variables everywhere... How to achieve code reuse in the shell?

  • well, if you don't use functions to set variables you dont have those kind of problems. if your function was some validation test on its arguments, and you did: validStrings "$var1" "$var2" && newVar=$var1$var2 you might find it a lot easier to get along. – mikeserv Dec 3 '15 at 3:38
  • 1
    returnValue is a global variable unless you use the keyword local. – pfnuesel Dec 3 '15 at 3:49
3

In Unix and GNU, the standard output of the function can be considered the return value.

Here's an example using shell command expansion $(...):

JoinStrings() {
    echo "$1$2"
}

joined_strings=$(JoinStrings string1 string2)

echo string1 and string2 joined are $(JoinStrings string1 string2)

There is a shell return statement for use in functions, which sets the exit code (status code) of the command. The exit code is a small integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.