How to return a value from bash function

Returning a variable from functions in bash script can be little tricky. Bash functions are not similar to functions in other languages but these are commands. This article will cover some ways you can return values from bash functions:

Return value using global variable

Global variable can be used to return value from a bash function. Here is sample code to demonstrate it. Save the following code to a file (say script1.sh) and run it.

#!/bin/bash
var1="oldval"
function test1() { 
 var1="newval" ;
}
test1
echo $var1

Here is the outcome from above code:

newval

In case you prefix variable var1 with local then global variable is not modified. Here is the code for it:

#!/bin/bash
var1="oldval"
function test1() { 
  local var1="newval" ;
}
test1
echo $var1

And the outcome for the above code is:

oldval

Return value using echo and subshell

Another approach is to use echo and call function using subshell command $(…). This is better approach whenever it can be used as it does not have to use global variable. Here is sample code for it:

#!/bin/bash
function test1() {
 echo "someval" ;
}
var1=$(test1)
echo $var1
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments