views:

73

answers:

5

I'd like to return a string from a bash function.

I'll write the example in java to show what I'd like to do:

public String getSomeString() {
  return "tadaa";
}

String variable = getSomeString();

The example below works in bash, but is there a better way to do this?

function getSomeString {
   echo "tadaa"
}

VARIABLE=$(getSomeString)
+4  A: 

There is no better way I know of. Bash knows only status codes (integers) and strings written to the stdout.

Philipp
A: 

You could use a global variable:

declare globalvar='some string'

string ()
{
  eval  "$1='some other string'"
} # ----------  end of function string  ----------

string globalvar

echo "'${globalvar}'"

This gives

'some other string'
fgm
A: 

You could have the function take a variable as the first arg and modify the variable with the string you want to return.

#!/bin/bash
function pass_back_a_string() {
         eval $1=foo
}

return_var=''
pass_back_a_string return_var
echo $return_var

Prints "foo"

bstpierre
+1  A: 

The way you have it is the only way to do this without breaking scope. Bash doesn't have a concept of return types, just exit codes and file descriptors (stdin/out/err, etc)

Daenyth
A: 

You could also capture the function output:

#!/bin/bash
function getSomeString() {
     echo "tadaa!"
}

return_var=$(getSomeString)
echo $return_var
# Alternative syntax:
return_var=`getSomeString`
echo $return_var

Looks weird, but is better than using global variables IMHO. Passing parameters works as usual, just put them inside the braces or backticks.

chiborg