1

Bash 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:

function 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 bash?

bodacydo
  • 69,885
  • 86
  • 222
  • 312
  • 1
    "Function" is really a poor choice of names for this bit of shell; "subroutine" would have been better, since they don't actually return a value. (Even `return` just sets the exit status, whose semantics have more in common with an exception than a return value.) – chepner Dec 03 '15 at 03:26

2 Answers2

2

Just output the value.

function JoinStrings {
    echo "$1$2"
}
JoinStrings a b         #ab
x=$(JoinStrings a bc)   #x is now abc
Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
2

You can use echo to "return" an arbitrary value:

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

cat="cat"
dog="dog"
catdog=$(join_strings $cat $dog)
echo $catdog
# catdog
Hunter McMillen
  • 56,682
  • 21
  • 115
  • 164