[prog] Returning a string from a function, in bash

Riccarda Cassini riccarda.cassini at gmx.de
Thu Apr 15 21:26:42 EST 2004


Hi everyone,

I'm trying to learn some shell scripting (in bash), and, at the risk
of outing myself as a total newbie, I'd like to get some advice on the
following question. Hope it's not too basic for this list.

In shell scripting, how do I return a string from a function, or more
specifically, how do I assign the return value to some variable?

I've already read the relevant sections of 'man bash' a couple of
times, but unfortunately, there aren't any examples for someone like
me...

What I'd like to do is probably best explained with a few lines of
perl code (which I'm slightly more familiar with):

  sub myfunc
  {
    my $arg = shift;
    # do something useful here...
    return "arg was: $arg";
  }
  
  $par = 'test';
  $var = myfunc($par);

(after executing this, I'd expect $var to be set to "arg was: test")

My initial attempt to achieve the same effect in shell syntax was:

  myfunc ()
  {
    local arg=$1
    return "arg was: $arg"
  }
  
  par=test
  var=myfunc($par)

Apparently no good, for more than one reason - as I gradually learnt
while trying to get rid of the various error messages this produced.
After some trial and error, I ended up with

  myfunc ()
  {
    local arg=$1
    echo "arg was: $arg"
  }
  
  par=test
  var=`myfunc $par`

This seems to work, so I basically could be happy with it. However, I'm
a little unsure as to whether this is the way one's supposed to do it.
Do I really have to use echo and backticks?  I'd just like to get a
quick confirmation from more experienced hackers, before I make massive
use of this technique in some code that other people might take a look
at some time in the future... ;-)

Thanks,

Riccarda




-- 
NEU : GMX Internet.FreeDSL
Ab sofort DSL-Tarif ohne Grundgebühr: http://www.gmx.net/info



More information about the Programming mailing list